Sie sind auf Seite 1von 274

UNIT-1

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.

Obtaining the Java SDK


Obtaining the Java SDK Download from Sun Web-site http://java.sun.com/j2se Choose your version Select your platform Download will be an installer file appropriate for your platform Installer .exe for windows rpm or self extracting file for Linux
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Obtaining the Java SDK


tar or self extracting file for SPARC To install, execute the installer program or extract from tar file.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Java Version History


Even though java is not very old, there are several key versions to be aware of: Java 1.0.2-First stable version . Not very useful. Java 1.1 (1997) -Security, Database connectivity (JDBC). Improved performance. -Most stable version 1.1.8 -Unstable versions 1.1.4 and 1.1.5 Java 1.2 (1998) Major Changes
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Java Version History


-Addition of Swing GUI (Mostly replaces AWT) -Improved Security -Enterprise computing. Java 1.3 (2000) - Many extended APIs added - Improved performance Java 1.4(2002) -Improved performance -Bug Fixes.etc.
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. #

Introduction to Java Cont.


Much of the syntax of Java is the same as C and C++. One major difference is that Java does not have pointers. However, the biggest difference is that you must write object oriented code in Java. Procedural pieces of code can only be embedded in objects. In the following we assume that the reader has some familiarity with a programming language. In particular, some familiarity with the syntax of C/C++ is useful.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Introduction to Java Cont.


In Java we distinguish between applications, which are programs that perform the same functions as those written in other programming languages, and applets, which are programs that can be embedded in a Web page and accessed over the Internet. Our initial focus will be on writing applications. When a program is compiled, a byte code is produced that can be read and executed by any platform that can run Java.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Importance and Features of Java


It is an object- oriented language developed by Sun in the mid 1990s. -Original language called Oak (renamed Java in 1995) -Intended for embedded systems Unlike C++, it was developed from scratch. The syntax is very similar to C .and OOP s features influenced by C++ Sun describes it as
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.

Features of Java Cont.


multi- threaded, and dynamic language Object Oriented -Designed to support object-oriented concepts OOPs is a programming that helps to organize complex programs through the use of inheritance, polymorphism and encapsulation.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Features of Java Cont.


-java is a true object oriented language. Almost everything in java is an object. All program code reside within objects and classes. Java have extensive sets of class arranged in package.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Features of Java Cont.


Distributed -Applications are constructed using objects. Objects can be distributed in multiple locations within a network environment.. -This allowed objects on two different computers to execute procedures remotely by using RMI (Remote Method Invocation).

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Features of Java Cont.


-Extensive

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.

How Java is Secure


Java provides a firewall between a network application and compiler. Java Compatible browsers can safely downloaded, java applet with fear of virtual infection or malicious intent like (private info as credit card number, bank account balance, password ) by searching the content of computer local file system.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Features of Java Cont.


Java achieves protection by confining java programs to java environment and not allowing it to access to other parts of computer. Architecture Neutral Compiled java (byte code) will run on any plateform which has a Java Virtual Machine. The JVM is available for almost all plateform. Even mainframes.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Features of Java Cont.


The compiler generates an architecture neutral object file format-the compiled code can run on many processors (8085,8086,386 etc.) give the presence of java runtime system.

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. #

Features of Java Cont.


Many database servers, Application servers, Web servers and web browsers contain a JVM. e.g. Oracle, Tomcat (Web Server), WebSphere (App server), BEA Weblogic (App server), Netscape and IE etc. High Performance Speed

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Features of Java Cont.


Multi-Threaded -Processes contain multiple threads of execution. -All threads share the same memory space. Dynamic -Java program is used to verify and resolve accesses to objects at run time
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Features of Java Cont.


Plateform Independency. How does Java do it? Java has been described as WORA (Write once , Run Anywhere) Because Java source code is compiled to byte code and the byte code is interpreted, Java code can be executed anywhere an interpreter is available. The Interpreter is call the JVM.
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

Java Bytecode Source. class

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. #

Features of Java Cont.


Interpreted -Java compiles to byte-code (not machine code). Byte code is interpreted. - JIT Compiler as a part of JVM which compiles byte code to machine code or executable code generated on piece by piece to machine not possible to compile entire java program into executable code all at once bcz. Java performs various runtime classes. .
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Features of Java Cont.


-Instead JIT compiles as it is needed during execution. -JIT produce non-portable executables.

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. #

Features of Java Cont.


Secure -All java code subject to security model. -java enables construction of virus free, temper free system.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Features of Java Cont.


Multitasking -More than one process running at the same time. -Every process has its own address space. -Context switching complex (A context switch is the computing process of storing and restoring the state (context) of a CPU such that multiple processes can share a single CPU resource).

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Features of Java Cont.


-Inter-process communication expensive (Inter Process Communication is a capability that allows one process to communicate with another process). Multithreading -More than one thread at one time (thread is a part of a process). -Address space is shared. -Context switching is simple. -Not Expensive (bcz. Of limited area).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

10

Applications, Applets & Servlet


Java programs are of three types: types: 1.Applications a standalone program executed from the operating system environment 2.Applets a short program designed to be incorporated within a Web document executed using a Web browser
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Applications, Applets & Servlet


3.Servlets It is a server side program similar to an applet. I It is defined in the java servlet application programming interface (API). It enables to extend the functionality of web servers. It is particularly used for producing dynamic web contents.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Building the java program


Java is case sensitive Java program must be entered in a file with file name as the class name. Every statement ends with a semicolon(;). Every application program has a main.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

11

Applications

helo.java

Java program source code

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.

helo.java javac helo.class

Program bytecode

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

12

Applet

helo.java javac

Same procedure as for Applications

helo.class

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Applet Cont.

helo.java javac helo.class A browser Netscape


#

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.

Java program consists of a named 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!"); } }
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.

main() in Java Cont.


In main(), there is only one parameter , String args[] declares a parameter named args, which is an array of String store character strings. In this case, args receives any command-line arguments present when the program is executed.

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.

Important Syntax Cont.


JDB- java debugger (Allows you to step through the program line at a time, set break points, and examine variables.) Syntax: jdb filename Javap- Java disassembler (It displays the meaning of byte code. It also display the accessible functions and data in a compiled class file. Syntax: javap filename
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

19

Important Syntax Cont.


Javah- It creates header and stub files that let you extend your java code with the c language. Syntax: javah filename JavadocIt creates HTML format documentation from java source code file. To use javadoc, you have to embed the statements /** and */. These statements are called documentation comment block. Syntax: javadoc filename
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Important Syntax Cont.


Appletviewer- Run applets (A java interpreter that executes java applet classes hosted by HTML.) Syntax: appletviewer filename.html Jar- Java archive (JAR) file generator. (Jar files allows multiple java classes and resources to be distributed in one compressed file.) Syntax: jar filename.jar inputfile name
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

Some Shortcut Keys.


F3- Display the last command F7- List all the command you already used F8- Instance retype command( e.g. dir *.* you just type d then press the F8 key to instantly retype the command). F9- It get input as Line number and go to the that command (e.g. Line No: 1 will go to first command)

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. #

Data Types Cont.


int long float double 32 bits signed integer 64 bits signed integer 32 bits signed floating point number 64 bits signed floating point number

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

21

Data Types Cont.


Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language Unicode allows Java to handle international characters for most of the worlds living languages, including Arabic, Armenian, Bengali, Bopomofo, Chinese (via unified Han), Cyrillic, English, Georgian,
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Data Types Cont.


Greek, Gujarati, Gurmukhi, Hebrew, Hindi (Devanagari), Japanese (Kanji, Hiragana and Katakana via unified Han), Kannada, Korean (Hangul via unified Han), Lao, Maylayalam, Oriya, Tai, Tamil, Telugu, Tibetan Unicode will make it much easier for non-English speaking programmers to write programs for English speaking users and vice versa.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Data Types Cont.


The Unicode Standard is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages and technical disciplines of the modern world. Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

22

Data Types Cont.


The Unicode Standard has been adopted by such industry leaders as Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys and many others. Unicode is required by modern standards such as XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML, etc., and is the official way to implement ISO/IEC 10646. It is supported in many operating systems, all modern browsers, and many other products. A 16-bit character encoding used in Java.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Constants and Variables


The simplest terms that appear in expressions are constants and variables. The value of a constant does not change during the course of a program. A variable is a placeholder for a value that can be updated as the program runs. A variable in Java is most easily envisioned as a box capable of storing a value.
total

42

(contains an int)
#

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Constants and Variables Cont.


Each variable has the following attributes: A name, which enables you to differentiate one variable from another. A type, which specifies what type of value the variable can contain. A value, which represents the current contents of the variable. The name and type of a variable are fixed.

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. #

Variable Declarations Cont.


type or class, name is an identifier that indicates the name of the variable, and value is an expression specifying the initial value. Most declarations appear as statements in the body of a method definition. Variables declared in this way are called local variables and are accessible only inside that method. Variables may also be declared as part of a class. These are called instance variables.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Operators and Operands


Decide the semantics of expression Meaning of operator given in language system

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.

Arithmetic Operator Cont.


Operators
+ - * / % += -= *= /= %= ++ -5/2 2 (Why isnt it 2.5 ?) 5%2 1 4/2 2 4%2 0 j += 6; j = j + 6;
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

NaN (Not a Number)


Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

a < b && b < c 3

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

26

Conditional Operator Cont.


Expr1 ? Expr2 : Expr3 (3 Terms Operator)

max = x > y ? x : y ;

if (x > y) max = x; else max = y;

m = a > b ? (c > a ? c : a) : (c > b ? c : b) ;

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Increment & Decrement Operator


++, - Prefix operator
n = 1; x = ++n; // x=2, n=2

Postfix operator
n = 1; x = n++; // x=1, n=2

Cannot use at expression, only at variable


(a + b)++ // error

Cannot apply at real type


Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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. #

Bitwise Operator Cont.


Bitwise Shift Operator
Shift left(<<)
x << y = x * 2y

Shift right(>>)
x >> y = x / 2y

Unsigned shift right(>>>)


Give this operator because Java does not support unsigned integer.

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

(int) 3.75 (float) 3 (float) (1 / 2) (float)1/2

===> ===> ===> ===>

3 3.0 0.0 0.5

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

Who will convert the type?


Implicit type conversion Carried out by compiler automatically Explicit type conversion Carried out by programmer using casting

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

30

Type Conversion Cont.


Widening Type Conversion (Automatic Conversion) Implicit conversion by compiler automatically-when the two types are compatible and the destination type is larger than the source type.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Type Conversion Cont.


Examples byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double

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

Type Conversion Cont.


Examples byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long, float
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Type Conversion Cont.


Type Conversion Prohibit boolean type Only Can covert into same type

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Mixing Numeric Data Types


Java will automatically convert int expressions to double values without loss of information int i = 5; double x = i + 10.5; To convert double expressions to int requires a typecasting operation and truncation will occur i = (int) (10.3 * x)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

32

Mixing Numeric Data Types Cont.


To round-up instead of truncating add 0.5 i = (int) (10.3 * x + 0.5)

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

Strings and Characters


String : sequence of character String s = Enter an integer value: ; Char c = A;
Concatenation Operator +

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.

The if statement Cont.


The if statement may have an optional else clause. Syntax if (expression) statement_1 else statement_2

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

35

The if statement Cont.


class test { public static void main(String[] args) { boolean bigger; int a = 2; int b = 1; bigger = (a > b); if (bigger) System.out.println(he wins"); else System.out.println(you win"); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Nested if statements Cont.


if (x) if (y) a = 1; else a = 2; if (x) { if (y) a = 1; else a = 2; }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Nested if statements
if (x) if (y) a = 1; else a = 2;

Avoid confusion by using brackets.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

36

Nested if statements Cont.


if (x){ { if (y) a = 1; } else a = 2;

Avoid confusion by using brackets.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The if-else-if structure


Syntax

if (condition1) statement1;

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The if-else-if structure

Syntax

if (condition1) statement1; else if (condition2) statement2;

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

37

The if-else-if structure


Syntax if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3;

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The switch statement


n The

switch statement provides a multiway decision.

char ch; switch (ch) {

}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

The switch statement Cont.


The switch statement provides a multi-way decision char ch; switch (ch) { case 'M' : case 'Q' : }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

38

The switch statement Cont.


The switch statement provides a multi-way decision.
char ch; switch (ch) { case 'M' : ShowMenu(); break; case 'Q' : exit(0); }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The while statement


The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: Syntax while (expression) { statements }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The while statement


The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. int i=5; while (i-- > 0) System.out.println("X");

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

39

The do-while statement


The do-while loop is a rarely used repetition structure. Syntax

do statement while (expression)

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The do-while Example


The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression);

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. #

The for statement


The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (initialization; termination; increment) { statement(s) }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

The for statement Cont.


When using this version of the for statement, keep in mind that: The initialization expression initializes the loop; it's executed once, as the loop begins. When the termination expression evaluates to false, the loop terminates. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

41

The for statement Cont.


class ForDemo {public static void main(String[] args) { for(int i=1; i<11; i++) { System.out.println("Count is: " + i); } } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

The for statement Cont.


int i, sum; for (i=1,sum=0;i<=3;++i){ sum += i; System.out.println(sum); }
ADVANTAGE All control information at the top.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Java Break Lable


In Java, break statement is used in two ways as labeled and unlabeled. break is commonly used as unlabeled. Labeled break statement is used for terminating nested loops. Nested loops are loops defined inside other loops in which the topper most loop is define under a label with any String value. In the example a label String value 'weisz' is defined above the outer most loop while.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

42

Java Break Label Cont.


In the code when if condition becomes true the break statement terminates the while loop under the label weisz.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Java Break Label Cont.


public class Java_Break_lable { public static void main(String args[]) { int modulo = 10, i = 0,j = 0; weisz: while(i < modulo){ for(;;i++){ for(;j < i;j++) System.out.println("modulo : " + modulo + "\t\ti : " + i); if (i == modulo)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Java Break Label Cont.


break weisz; else { modulo--; continue; } } } System.out.println("\nValue at which the nested loops defined under label 'weisz' is : " + modulo); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

43

Java Break continue


Java has two keywords break and continue in its branching category. 'break' allows users to give end to a loop whereas with 'continue' statement flow of control inside a loop can be continued even when the specified loop condition is false. 'continue' statement returns the program control from the point where it is passed.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Java Break continue


public class Java_Break_continue { public static void main(String argv[]) { char [] c = {'J','a','v','a','*'}; String str[] = {"continue","break","statement","example"}; char c_1 = c[4]; byte i = 0;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Java Break continue


do{ System.out.print(" " + c[i]); i++; if(c[i] == c_1) break; else continue; }while(c.length > i);

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

44

Java Break continue


System.out.println(" "); for(int j = 0; j < str.length; j++){ System.out.print(str[j] + " "); if(j < str.length) continue; // from here the program control is returned back System.out.println("woooooooooooooooooo"); } } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Java Break continue


When it reaches a return statement throwing an exception, whichever occurred first. The return statement is used to return the value within the body of method. The method declared void does not return any value. In case you try to get the return value from void the code show you a compiler error.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

45

Java Break continue


class ReturnValue { public static void main (String[] args) { System.out.println("The Biggest Number is: " +GetBiggestNumber(10, 15, 20)); } public static int GetBiggestNumber (int num1 , int num2, int num3) { int biggest = 0;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Java Break continue


if ((num1 > num2) && (num1 > num3)) biggest = num1; else if ((num2 > num3) && (num2 > num1)) biggest = num2; else biggest = num3; return biggest; } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

Introduction to class Cont.


Static methods and fields belong to the class itself Others belong to instances.

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. #

Example of a class Cont.


class tria { public static void main(String a[]) { tri t1=new tri(); //object created t1.base=10.0;//assignment t1.height=20.0; t1.findarea(); } }
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. #

new operator Cont.


1. Declare a variable of the class type; 2. Physical copy of an object is assigned it to that variable. The above two steps are achieved by new operator. Objects are initialized when they are declared. The default value is null.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

new operator Cont.


triangle t;// Declares as a reference to an object of type
// Triangle.

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. #

Garbage Collector Cont.


When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the objects memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection .

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Garbage Collector Cont.


This is a potential programming pitfall because some programmers, especially C++ programmers, might initially mistake finalize( ) for the destructor in C++, which is a function that is always called when an object is destroyed. But it is important to distinguish between C++ and Java here, because in C++ objects always get destroyed (in a bug-free program), whereas in Java objects do not always get garbage-collected. Or, put another way:
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

Call by Value Cont.


class value { void change(int i) { i=i*20; System.out.println("Inside method:"+i); } } class call { public static void main(String f[])
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Call by Value Cont.


{ value v=new value(); int x=20; System.out.println("Before call:"+x); v.change(x);//calling System.out.println("After call:"+x); } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Call by Value Cont.


Output: C:\d>javac call.java C:\d>java call Before call:20 Inside method:400 After call:20

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.

Call by reference Cont.


This means that any change made to the object by the called method is reflected in the calling method. In java objects are passed by using call by reference.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Call by reference Cont.


class test { int i; test(int j) { i=j; } //pass by reference void change(test s)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

53

Call by reference Cont.


{ s.i=s.i*20; System.out.println("inside method:"+s.i); } } class reference { public static void main(String f[]) { test t1=new test(20);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Call by reference Cont.


test t1=new test(20); System.out.println("Before call:"+t1.i); t1.change(t1);//calling here System.out.println("After call:"+t1.i); } }

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

Static modifier Cont.


Important about static
Static method cannot use non-static methods and variables. They cannot refer this or super. this- this is used inside any method to refer to the current object. i.e. this is always a reference to an object on which the method was invoked. Box(double w, double h) { this.width=w; this.height=h; }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

public Circle() { r = 1.0; } // better: public Circle() { this(1.0); }


This() refers to a constructor for the class

// 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

Copy constructor Cont.


public copy(copy c) //copy constructor { a=c.a; b=c.b; } void view() { System.out.println("a="+a +" "+"b="+b); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Copy constructor Cont.


class copytest { public static void main(String d[]) { copy c=new copy(10,15); System.out.println("First constructor"); c.view(); copy c1=new copy(c); // invoke copy constructor System.out.println("Second constructor"); c1.view(); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Copy constructor Cont.


C:\d>javac copytest.java C:\d>java copytest First constructor a=10 b=15 Second constructor a=10 b=15 C:\d>

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.

Inheritance in Java Cont.


Syntax for Class declaration that inherits a superclass class subclass-name extends superclassname { // body of class } Subclass have more functionality than superclass
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

58

Inheritance in Java Cont.


Member Access: A class member declared as private will remain private to its class .It is not accessible by any code outside its class including subclass. Advantage of Inheritance Once a superclass is constructed that define attribute common to a set of objects ,it can be used to create any numbers of more specific subclasses
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Types of Inheritance Cont.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

59

Types of Inheritance Cont.


Multilevel-There is at least two parent class. One base class and one derived class, and derived class treated as parent class for another child class.

Person

Person

Employee Doctor Part-Time Employee

Neuro-Surgon

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Types of Inheritance Cont.


Multiple- More than one base class and one derived class, But in java only one base class is useful. //Multiple inheritance is not supported by java.
Vehicle Asset Eagle Lion

Employee Vehicle

Griffin

Note: We can implement it by using Interfaces.


Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Types of Inheritance Cont.


Hierarchical- More than one child class has same parent class.

Person

Employee

Customer

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

60

Types of Inheritance Cont.


Hybrid- Mixture of more than one inheritance.
e.g.
Person

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;

note the location of the []

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

63

Creating Array Cont.


It must be created (ie. memory must be allocated for the array)
int[] grades; // declaration

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.

Creating Array Cont.


When an array is created, all of its elements are automatically initialized 1. 0 for integral types 2. 0.0 for floating point types 3. false for boolean types 4. null for object types

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Creating Array Cont.


e.g.
array indices
0 0 0 0 0

grades

int[] grades = new int[5];

1 2

maximum array index is length -1

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

64

Initializing and Using Arrays


Because array elements are initialized to 0,the array should be initialized with usable values before the array is used. This can be done with a loop Arrays have a length attribute which can be used for bounds checking e.g. Elements are accessed using an index and []

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Initializing and Using Arrays


int[] sequence = new int[5]; for (int i=0; i< sequence.length; i++) { sequence[i] = i * 25; }

Array element being accessed. In this case, it is being assigned a value.

array length: ensures loop won't go past end of the array


#

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Using initializer lists


Another way of initializing lists is by using initializer lists. The array is automatically created The array size is computed from the number of items in the list.

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

Array Bounds Checking

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.

Array Bounds Checking


ArrayIndexOutOfBoundsException int[] sequence = new int[5]; sequence[0] = 50; sequence[1] = 60; sequence[-1] = 100; sequence[5] = 30; // ok // ok // Exception // Exception

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The main() method


You may recall that the main method takes an array of String objects as a parameter. This array of Strings holds the command line parameters which were passed to the java program when it was started
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
Array holding command line parameters
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

66

Command line parameters


name of class containing the main() method
java HelloWorld This is a test, Jim
args

0 1 2 3 4

This is a test, Jim

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Multi-dimensional Array

Arrays with multiple dimensions can also be created.


declaration syntax:

type[][] arrayName;

each [] indicates another dimension

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.

Multi-dimensional Array Cont.


e.g.
int[][] grades = new int[20][5]; for(int i = 0; i< 20; i++) for(int j = 0; j<5; j++) grades[i][j] = 100;

String[][] colours =

{{"Red", "Green", "Blue"}, {"Cyan", "Magenta", "Yellow"}, {"Russet", "Mauve", "Orange"}};

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.

Using initializer lists


e.g. String array

String[] colours = { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

String Array Example


class StringCharacter { static String[] roseindia={"chanan","tapan","Amar ","santosh","deepak"}; public static void main(String args[]){ for(int i=0;i<5;i++){ System.out.println(roseindia[i]); } } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

68

The String Class


An object of the String class represents a string of characters. The String class belongs to the java.lang package, which does not require an import statement. Like other classes, String has constructors and methods. Unlike other classes, String has two operators, + and += (used for concatenation). String objects are handled specially by the compiler. String is the only class which has "implicit" instantiation.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

The String Class Cont.


The String class is defined in the java.lang package. Strings are immutable. The value of a String object can never be changed. For mutable Strings, use the StringBuffer class.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The String Class Cont.


String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data); Here are some more examples of how strings can be used: System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2,3); String d = cde.substring(1, 2);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

69

The String Class Cont.


The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The String Class Cont.


The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling,
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

The String Class Cont.


Joy, and Steele, The Java Language Specification. Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

70

The String Class Cont.


A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String. The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Creating String Objects


Normally, objects in Java are created with the new keyword. String name; name = new String("Craig"); However, String objects can be created "implicitly":
String name; name = "Craig";
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Creating String Objects Cont.

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

Commonly used String methods


The String class has many methods. The most commonly used are: length() - returns the number of characters in the String charAt() - returns the character at the specified index equals() - returns true if two strings have equal contents compareTo() -returns 0 if equal, -# if one String is "less than the other, +# if one String is "greater than" the other.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Commonly used String methods


indexOf() - returns the index of specified String or character substring() -returns a portion of the String's text toUpperCase(), toLowerCase() - converts the String to upper or lower case characters

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

String Examples Cont.


e.g.
String grade = "B+"; double gpa = 0.0; if (grade.charAt(0) == 'B') gpa = 3.0; if (grade.charAt(1) == '+') gpa = gpa + 0.3;

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Testing Strings for Equality


Important note: The == operator cannot be used to test String objects for equality Variables of type String are references to objects (ie. memory addresses) Comparing two String objects using == actually compares their memory addresses. Two separate String objects may contain the equivalent text, but reside at different memory locations. Use the equals method to test for equality.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

The StringBuffer Class Cont.


StringBuffer objects are similar to String objects Strings are immutable StringBuffers are mutable The StringBuffer class defines methods for modifying the String value insert() append() setLength()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

73

The StringBuffer Class


To clear a StringBuffer, set it's length to 0 StringBuffer nameBuffer = new StringBuffer("Joe"); [...] nameBuffer.setLength(0); // clear StringBuffer

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

String Tokenizer Cont.


hasMoreToken() // Test whether more tokens are avail in the string nextToken // Returns the next token in the string Note: import java.util.*; package.

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.

StringTokenizer Example Cont.


tokenCount = st.countTokens(); System.out.println("Number of tokens = " + tokenCount); while (st.hasMoreTokens()) // make sure there is stuff to get { words[idx] = st.nextToken(); idx++; } for (idx=0;idx<tokenCount; idx++) { System.out.println(words[idx]); } } }
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. #

Wrapper Classes Cont.


Integer Long Float Double In wrapper class first character is upper case Character and Integer is not abbreviated as the type char and int. Byte,Boolean,Short,Integer,Long,Float,Doubl _e are subclass of the abstract class number.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Wrapper Classes Cont.


These wrapper classes encapsulate(or) wraps up a primitive type. So that a variable can be represented by an object when necessary. Theses classes also have a constants MAX_VALUE and MIN_VALUE.

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.

Integer Class Cont.


toHexString(int n) // returns a String that contain hexadecimal equivalent of n toOctalString(int n) // returns a String that contain Octal equivalent of n.etc.

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. #

The System class


The System class: It is one of the most important classes in the java.lang package. It provide a standard interface to standard input,ouput and error. System.in.read(); //input System.out.println(helo); //output System.err.println(Error); //error

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The Class Class


The Class Class: This is used to find runtime state of an object or interface. Objects of type class are created automatically when classes are loaded. getName()=returns the complete name of the class or interface of the invoking object. getSuperClass()=returns the super class of the invoking object.

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.

Method Overriding Example


class a { void show() { System.out.println("Inside Superclass"); } } class b extends a { b() { super.show();// if super is not used only sublass output will be displayed. }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

82

Method Overriding Example


void show() { System.out.println("Inside Subclass"); } } class override { public static void main(String s[]) { b b1=new b(); b1.show(); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Abstract Class Example


abstract class A { abstract void callme(); void callmetoo() { System.out.println(This is a concrete method); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Abstract Class Example


class B extends A{ void callme() { System.out.println(Bs implementation of callme); } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

85

Abstract Class Example


class demo { public static void main(String s[]) { B b=new B(); b.callme(); b.callmetoo(); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Abstract Class Example


Output: Bs implementation of call me This is a concrete method

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Difference between concrete and abstract class

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

Difference between concrete and abstract class

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. #

final variable Example


public class Sphere { public static final double PI = 3.141592653589793; // this is essentially a constant public final double radius; public final double xpos; public final double ypos; public final double zpos; Sphere(double x, double y, double z, double r)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

final variable Example Cont.


{ radius = r; xpos = x; ypos = y; zpos = z; } [...]} Any attempt to reassign radius, xpos, ypos, zpos will meet with a compile error. In fact, even if the constructor doesn't set a final variable, attempting to set it outside the constructor will result in an compile error.
#

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. #

Introduction Interface Cont.


By providing interface keyword java allows you to fully utilize the one interface, multiple methods aspect of polymorphism. Note: Since Java has single inheritance of implementation - you can extend only one class.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

89

Introduction Interface Cont.


But Java has multiple interface inheritance. All methods in an interface are implicitly abstract. Each class that implements the interface must implement all its methods. Methods in an interface are always public. Fields in an interface are always static and final.

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

Note: When you implement an interface method, it must be declared as public.


Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Java Interface to achieve multiple inheritance

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.

Difference between Abstract class and Interface

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. #

Difference between Abstract class and Interface

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

Difference between Abstract class and Interface

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. #

Difference between Abstract class and Interface

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

Extending Interface Example


interface one { void print1(); void print2(); } interface two extends one { void print3(); }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Putting classes together by using package

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. #

Benefits of Package(s) Cont.


Classes in packages can be hidden if we dont want other packages to access them. Packages also provide a way for separating design from coding.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Types of Package(s) Cont.


Since packages are collection of related classes. These are of two types: 1. Predefined package (Java API Package, or Built-in package) 2. User-Defined package

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.

Predefined package Cont.


java.util Contains classes such as vectors, hash tables, date etc. java.io Stream classes for I/O java.awt Classes for implementing GUI windows, buttons, menus etc.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Predefined package Cont.


java.net Classes for networking java.applet Classes for creating and implementing applets

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

97

Accessing Classes from Packages


There are two ways of accessing the classes stored in packages: Using fully qualified class name java.lang.Math.sqrt(x); Import package and use class name directly. import java.lang.Math Math.sqrt(x);
import package.class; import package.*;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

Creating Packages Cont.


package myPackage; public class ClassA { // class body } class ClassB { // class body }

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. #

Creating Sub Packages


Classes in one ore more source files can be part of the same packages. As packages in Java are organised hierarchically, sub-packages can be created as follows: package myPackage.Math package myPackage.secondPakage.thirdPackage

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Creating Sub Packages Cont.


Store thirdPackage in a subdirectory named myPackage\secondPackage. Store secondPackage and Math class in a subdirectory myPackage.

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. #

Accessing a Package Cont.


All classes/packages from higher-level package can be imported as follows: import myPackage.*;

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Protection and Packages


All classes (or interfaces) accessible to all others in the same package. Class declared public in one package is accessible within another. Non-public class is not Members of a class are accessible from a difference class, as long as they are not private protected members of a class in a package
are accessible to subclasses in a different class
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 Yes Yes

Yes Yes Yes No

Yes Yes No No

Yes No No No

Class in package

Subclass in different package Non-subclass different package

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Adding a Class to a Package


Consider an existing package that contains a class called Teacher:
package pack1; public class Teacher { // class body }

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

Adding a Class to a Package Cont.


Define the public class Student and place the package statement before the class definition as follows:
package pack1;

package pack1; public class Student { // class body }

class Teacher

class Student

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Adding a Class to a Package Cont.


Store this in Student.java file under the directory pack1. When the Student.java file is compiled, the class file will be created and stored in the directory pack1. Now, the package pack1 will contain both the classes Teacher and Student.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Packages and Name Clashing


When packages are developed by different organizations, it is possible that multiple packages will have classes with the same name, leading to name classing.
package pack2; package pack1;

class Teacher class Student

class Student class Courses

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

102

Packages and Name Clashing


We can import and use these packages like: import pack1.*; import pack2.*; Student student1; // Generates compilation error

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Handling Name Clashing


In Java, name classing is resolved by accessing classes with the same name in multiple packages by their fully qualified name. Example: import pack1.*; import pack2.*; pack1.Student student1; pack2.Student student2; Teacher teacher1; Courses course1;

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Extending a Class from Package


A new class called Professor can be created by extending the Teacher class defined the package pack1 as follows:
import pack1.Teacher; public class Professor extends Teacher { // body of Professor class // It is able to inherit public and protected members, // but not private or default members of Teacher class. }
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.

Review Questions Cont.


Q3) What is the output of following { float f4 = -5.5f; float f5 = 5.5f; float f6 = -5.49f; float f7 = 5.49f; System.out.println("Round f4 is " + Math.round(f4)); System.out.println("Round f5 is " + Math.round(f5)); System.out.println("Round f6 is " + Math.round(f6)); System.out.println("Round f7 is " + Math.round(f7)); } a)Round f4 is -6 Round f5 is 6 Round f6 is -5 Round f7 is 5 b)Round f4 is -5 Round f5 is 6 Round f6 is -5 Round f7 is 5
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Review Questions Cont.


Q4) What is the output of the following StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2= new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3)); a) false false false dar b) false true false Poddar c) Compiler Error d) true true false dar
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

105

Review Questions Cont.


Q5) What is the output (Assuming written inside main) String s1 = new String("amit"); String s2 = s1.replace('m','i'); s1.concat("Poddar"); System.out.println(s1); System.out.println((s1+s2).charAt(5)); a) Compile error b) amitPoddar o c) amitPoddar i d) amit i
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Review Questions Cont.


Q6)1 Boolean b1 = new Boolean("TRUE"); 2 Boolean b2 = new Boolean("true"); 3 Boolean b3 = new Boolean("JUNK"); 4 System.out.println("" + b1 + b2 + b3); a) Comiler error b) RunTime error c)truetruefalse d)truetruetrue

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions Cont.


Q7) What will be output of the following program { Float f1 = new Float("4.4e99f"); Float f2 = new Float("-4.4e99f"); Double d1 = new Double("4.4e99"); System.out.println(f1); System.out.println(f2); System.out.println(d1); } a) Runtime error b) Infinity -Infinity 4.4E99 c) Infinity -Infinity Infinity d) 4.4E99 -4.4E99 4.4E99

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

106

Review Questions Cont.


Q8) What is the output of following Double d2 = new Double("-5.5"); Double d3 = new Double("-5.5"); System.out.println(d2==d3); System.out.println(d2.equals(d3)); a) true true b) false false c) true false d) false true
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Review Questions Cont.


Q9) Which of the following wrapper classes can not take a "String" in constructor 1)Boolean 2) Integer 3) Long 4) Character 5) Byte 6) Short Q10) What output is displayed as the result of executing the following statement? System.out.println("// Looks like a comment."); // Looks like a comment The statement results in a compilation error Looks like a comment No output is displayed

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions Cont.


Q11)In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
It must have a package statement It must be named Test.java It must import java.lang It must declare a public class named Test

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

107

Review Questions Cont.


Q12)On successful compilation a file with the class extension is created. a) True b) False Q13)The Java source code can be created in a Notepad editor. a) True b) False

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions Cont.


Q14)The Java Program is enclosed in a class definition. a) True b) False Q15)When a string literal is used in the program, Java automatically creates instances of the string class. a)True b)False

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions cont..


Short answer type Questions Q1)What is Java? Q2)How to define an Abstract class? Q3)How to define an Interface in Java ? Q4)If a class is located in a package, what do you need to change in the OS environment to be able to use it? Q5)What is NullPointerException and how to handle it? Q6)What is the difference between the Boolean & operator and the && operator? Q7)What is the purpose of finalization?

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

108

Review Questions cont..


Q8)How can a subclass call a method or a constructor defined in a superclass? Q9)What is the difference between static and non-static variables? What is a static method? Q10) Which class should you use to obtain design information about an object?

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions cont..


Long answer type Questions Q1)What's the difference between an interface and an abstract class. Explain with examples? Q2)How Packages allow grouping of related classes into a single united.Explain with example? Q3)What are wrapper classes in java. Explain with example? Q4)What's the difference between String and StringBuffer class.Explain with example? Q5)How interacfes are helpful to implement multiple inheritance in java. Explain with example. Q6)How one can extend the interface. Explain with example? Q7)Differentiate between Java and C++? Q8)What is static keyword in java.Explain with example?
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Review Questions cont..


Q9) How interfaces are helpful to implement polymorphism. Explain with example? Q10)How to design a package. What is the usage of javac d option?

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

Exception & Error


What is the difference between error and an exception? An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error, StackOverFlow. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Exception & Error


Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

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. #

Exception Example Cont.


The stack trace will always show the sequence of method invocations that led up to the errors.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Exception Example Cont.


class excp { static void sub() { int d=0; int a=10/d; } public static void main( String s[]) { excp.sub()}}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

114

Exception Example Cont.


Output: Java.lang.ArithmeticException: / by zero at excp.subroutine(excep.java:4) at excep.main(excep.java:7) The bottom of the stack is mains line 7, which is the call to sub(), which caused the exception at line 4.

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

Multiple Catch Cont.


an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after try/catch block.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Multiple catch Example


class multi{ public static void main(String s[]) { try { int a=s.length; System.out.println("a="+a); int b=42/a; int c[]={1}; c[42]=99; }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Multiple catch Example Cont.


catch(ArithmeticException e) { System.out.println("divide by zero"+e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds"+e); } System.out.println("After try/catch blocks"); } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

116

Multiple catch Example Cont.


C:\java\bin>javac multi.java C:\java\bin>java multi a=0 divide by zero java.lang.ArithmeticException: / by zero After try/catch blocks C:\java\bin>javac multi.java C:\java\bin>java multi a=0 divide by zero After try/catch blocks
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Nested try Example


This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the java runtime system will handle the exception.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

117

Nested try Example


class nesttry { public static void main(String agrs[]) try{ int a=args.length; int b=42/a; System.out.println(a= + a); try{ if (a==1) a=a/(a-a); //divide by zero if (a==2) { int c[]={1}; c[42]=99; }}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Nested try Example Cont.


catch (ArrayIndexOutOfBoundsException e) { System.out.println(Array Index out-ofBounds: + e ); } }catch(ArithmeticException e){ System.out.println(Divide by0:+e); } } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Nested try Example Cont.


C:>java nesttry Divide by0; java.lang.ArithmeticException: / by zero C:\> java nesttry on a=1 Divide by0; java.lang.ArithmeticException: / by zero C:\>java nesttry one two a=2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException
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

throw Example Cont.


public static void main(String args[]){ try { demproc(); }catch (NullPinteException e){ System.out.println(Recaught: +e); }}} Resulting output: Caught inside demoproc. Recaught: java.lang.NullPointerException: demo

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

throw Example Cont.


throw new NullPointerException(demo); Here, new is used to construct an instance of NullPointerException. All of javas builtin run time exceptions have at least two constructors: one with no parameter, and one that takes a string parameter.
In the second form the argument specifies a string that describes the exception.

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

throws Example Cont.


general form:type method-name(parameter-list) throws exception-list { //body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

throws Example Cont.


class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println( Inside throwOne.); Throw new IllegalAccessException (demo); } public static void main(String args[]){ try { throwOne(); }

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.

finally Example Cont.


class finallyDemo{ static void procA(){ try{ System.out.println(inside procA); throw new RuntimeException(demo); } Finally { System.out.println(ProcAs finally); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

122

finally Example Cont.


static void procB(){ try{ System.out.println(inside procB); return; }finally{ System.out.println(procBs finally); }} static void procC(){ try{ System.out.println(inside procC); }finally{ System.out.println(procCs finally); }}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

finally Example Cont.


public static void main(String args[]){ try{ procA(); }catch(Exception e){ System.out.println(Exception caught); } procB(); procC(); } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

finally Example Cont.


Out put: Inside procA procAs finally Exceptioncaught Inside procB procBs finally Inside procC procCs finally

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

123

Javas Built-in Exception


Unchecked
ArithmeticException Arithmetic error, such as divided-by-zero ArrayIndexOutOfBoundsException Array index is out-of-bounds ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid cast IlligalArgumentException Illigal argument used to invoke a method IlligalMonitorStateException Illigal monitor operation, such as waiting on an unlocked thread. IlligalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out-of-bound NegativeArraySizeException Array created with a negative size.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Javas custom Exception


throw- is used to throw an exception explicitly. Creating your own Exception Subclasses You can create your own Exception types to handle situations specific to your program. String toString(), Returns a string object containing a description of the exception.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Custom Exception Example


class user-e { public static void main(String s[]) { int marks=15; try { if(marks<30) throw new myException(); else System.out.println(PASS);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

124

Custom Exception Example Cont.


} catch(myException e) { System.out.println(e.toString());//returns a string that describes the object } } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Custom Exception Example Cont.


class myException extends Exception { myException() { super(FAIL); } } Output:myException:FAIL
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.

Application of Thread Cont.


A single game has all these elements being processed at the same time. The program has been divided into three sub-units and each subunit is handled by a thread. Java has built-in support for threads. A major portion of the java architecture is multithreaded.
In java programs, the most common use of a thread is to allow the applet to accept input from user and at the same time , display animation in another part of the screen.
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

Thread Class Cont.


AND Access_specifier <class_name> implements runnable { //body }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Thread and Process


The microprocessor allocates memory to the processes that we execute. Each process occupies its own address space (memory). However all the threads in a process share the same address space. Therefore, resources like memory, devices, data of a program, and environment of a program are available to all the threads of that program A thread is also known as lightweight process or execution context
#

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Thread and Process Cont.


This is because there is fewer overloads on the processor when it switches from one thread to another than it switches from one process to another. Processes are therefore heavyweight process.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

129

Processes Vs. Threads


Processes Completely separate, unrelated concurrent execution on the level of the operating system. (eg multiple programs running at the same time) Threads Concurrent units of execution within a given program. (e.g. pulling down a menu while loading a web page within a web browser)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Life Cycle of a Thread

Blocked

New

Ready

Running

Done

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Life Cycle of a Thread Cont.

blocked for IO sleep wait

notify, timer, IO available

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

130

Life Cycle of a Thread Cont.


Once you create a Thread Class. It Instantiate the Thread and invoke the method start. It intern triggers the run method on the Thread. Once the run method is completed, The thread will be in dead state. Ready-to-run A thread starts its life cycle with a call to start(). For example
MyThread aThread = new MyThread();
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Life Cycle of a Thread Cont.


aThread.start(); A call to start() will not immediately start thread's execution but rather will move it to pool of threads waiting for their turn to be picked for execution. The thread scheduler picks one of the readyto-run threads based on thread priorities. Running The thread code is being actively executed by the processor. It runs until it is swapped out, becomes blocked, or voluntarily give up its turn with this static method
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Life Cycle of a Thread Cont.


Thread.yield();Please note that yield() is a static method. Even if it is called on any thread object, it causes the currently executing thread to give up the CPU. Waiting A call to java.lang.Object's wait() method causes the current thread object to wait. The thread remains in "Waiting" state until some another thread invokes notify() or the notifyAll() method of this object. The current thread must own this object's monitor for calling the wait().
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

131

Life Cycle of a Thread Cont.


Sleeping Java thread may be forced to sleep (suspended) for some predefined time. Thread.sleep(milliseconds); Thread.sleep(milliseconds, nanoseconds);

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Life Cycle of a Thread Cont.


Please note that static method sleep() only guarantees that the thread will sleep for predefined time and be running some time after the predefined time has been elapsed. For example, a call to sleep(60) will cause the currently executing thread to sleep for 60 milliseconds. This thread will be in ready-torun state after that. It will be in "Running" state only when the scheduler will pick it for execution. Thus we can only say that the thread will run some time after 60 milliseconds.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Life Cycle of a Thread Cont.


Blocked on I/O A java thread may enter this state while waiting for data from the IO device. The thread will move to Ready-to-Run after I/O condition changes (such as reading a byte of data). Blocked on Synchronization A java thread may enter this state while waiting for object lock. The thread will move to Ready-to-Run when a lock is acquired.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

132

Life Cycle of a Thread Cont.


Dead
A java thread may enter this state when it is finished working. It may also enter this state if the thread is terminated by an unrecoverable error condition.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Life Cycle of a Thread Cont.


The OS can interrupt the thread at any time while it is running, and allow any other thread to run. Threads can put themselves into a wait state until another thread wakes them up.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Single threaded and Multithreaded


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.

133

Single threaded and 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. #

Single threaded and Multithreaded Cont.

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.

Single threaded and Multithreaded Cont.

OR Access_specifier <class_name> implements runnable { //body }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

134

Single threaded and Multithreaded Cont.

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. #

Single threaded and Multithreaded Cont.

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.

Single threaded and Multithreaded Cont.

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

Extending Thread Cont.


//This is the entry point for the second thread public void run() { try { for(int i=5;i>0;i--) System.out.println("Child Thread"+i); Thread.sleep(5000); }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Extend Thread Cont.


catch(InterruptedException e) { System.out.println("Child Interrupted");} System.out.println("Exiting child thread"); }} class ExtendThread { public static void main(String s[]) { new NewThread(); // create a new thread
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Extend Thread Cont.


try { for(int i=5;i>0;i--) System.out.println("Main Thread"+i); Thread.sleep(10000); } catch(InterruptedException e) { System.out.println("Main thread Interrupted");} System.out.println("Main thread exiting"); }}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

137

Thread Example Cont.


The child thread is created by instantiating an object of NewThread, Which is derived from Thread. Note: the call to super() inside NewThread. This invokes the following form of the Thread constructor: public Thread(String threadName) Where, threadName specifies the name of the thread.

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.

Implementing Runnable Cont.


Inside run(), you will define the code that constitutes the new thread. run() can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run() returns.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

138

Implementing Runnable Cont.


After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread(Runnable threadob,String threadName) In this constructor, threadob is an instance of a class that implements the Runnable interface.This defines where execution of the thread will begin, the name of the new thread is specified by threadName.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Implementing Runnable Cont.


After the new thread is created, it will not start running until you call its start() method, which is declared within Thread. void strat() // it executes call to run

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Implementing Runnable Cont.


class NewThread implements Runnable { Thread t; NewThread() { //create a new thread i.e. second thread t=new Thread(this,"Demo Thread"); System.out.println("Child THread"+t); t.start();//start the thread }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

139

Implementing Runnable Cont.


// This is the entry point for the second thread public void run() { try { for(int i=5;i>0;i--) System.out.println("Child THREAD"+i); Thread.sleep(500); }catch(InterruptedException e) {System.out.println("child interrupted");} System.out.println("child thread exited");}}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Implementing Runnablen Cont.


class ThreadDemo { public static void main(String f[]) { new NewThread();//create a new thread try { for(int i=5;i>0;i--) System.out.println("main Thread"+i); Thread.sleep(1000); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Creating Multiple Threads


catch(InterruptedException e) {System.out.println("Main interrupted");} System.out.println("Main thread exited"); }}
Creating Multiple threads We have been using only two threads: the main thread and one child thread. However, your program can spawn as many threads as it needs. e.g. the following program creates three child threads:

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

140

Creating Multiple Threads Cont.


class NewThread implements Runnable { String name;// name of thread Thread t; NewThread(String threadname) { name=threadname; t=new Thread(this, name); System.out.println("New Thread"+":"+t); t.start(); //start the thread}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Creating Multiple Threads Cont.


class MultiThreadDemo { public static void main(String f[]) { new NewThread("One"); new NewThread("Two"); new NewThread("Three"); try { //for(int i=5;i>0;i--) //System.out.println(name+":"+i);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Creating Multiple Threads Cont.


Thread.sleep(10000); } catch(InterruptedException e) { System.out.println("main thread Interrupted"); } System.out.println("main thread exiting"); } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

141

Creating Multiple Threads Cont.


//this is the entry point for thread public void run() { try { for(int i=5;i>0;i--) System.out.println(name+":"+i); Thread.sleep(1000); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Creating Multiple Threads Cont.


catch(InterruptedException e) { System.out.println(name+"Interrupted"); } System.out.println(name+"::"+"exiting"); } }

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

Thread Methods Cont.


There are two ways to determine whether a thread has finished . First-You can call isAlive() on the thread. final boolean isAlive() The isAlive() method returns true if the thread upon which it is called is still running, it returns false otherwise. Second-While isAlive() is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Thread Method Example


final void join() throws InterruptedException

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

Waiting for notification


As defined in object, every object has a wait(), notify(), and notifyAll() method. These should never be overridden They can only be called from inside synchronized blocks, and they only effect other threads in synchronized blocks which are synchronized on the same object.
Note that you dont specify what is being awoken in notify(). If there are more than 1 thread waiting on the same condition, you have no control of which awakens. notify() only awakens 1 thread. notifyAll() awakens all threads.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

Input/Output Programming Cont.


Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. Java includes the import statement to bring certain classes, or entire packages, into visibility. Import statement will save a lot of typing.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Input/Output Programming Cont.


System.in (Object) - read input from the user. - Whatever the users types the return type will always be a string because of the wrapping.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Input/Output Programming Cont.


Stream-A stream is an abstraction that either produce or consume information. A stream is linked to a physical device by the java I/O system. An input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise an output stream may refer to console, a disk file, or a network socket.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

146

Input/Output Programming Cont.


BufferedInputStreams work on byte streams. BufferedReaders work on character streams. byte streams contain bytes each 8-bit long. character streams contain (Unicode) characters each 16-bit long. Before the JDK1.1, you could only use byte streams. However, if you wanted to read in strings, you were in trouble, cause the method to do that did not properly convert bytes to characters.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Input/Output Exception Example


import java.io.*; class system { public static void main(String s[]) throws IOException { String str; System.out.print("Enter the string "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); str=br.readLine(); //Read string from console System.out.println(str); }}
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.

java.io Abstract Classes


There are 4 abstract classes for java.io that are very analogous to one another, but they do slightly different things. Reader Character Stream Writer InputStream Byte Stream OutputStream

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

148

java.io Abstract Classes Cont.


Each of these abstract classes has several concrete subclasses, that handles the differences between the various devices, such as disk files, network connection and even memory buffers. The above four abstract classes define several key methods that the other stream classes implements.Two most important methods are: read(), and write()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Character Stream Cont.


Where buf - the input buffer. offset - the offset in the buffer of the first byte to read. length - the maximum number of bytes to read from the buffer.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

149

Character Stream Cont.


Character stream classes through reading from and writing to a file: Character stream classes supports input and output for Unicode characters. The FileReader class allows to read characters from a file. FileWriter class allows you to write the characters to a file system.

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.

Byte Stream Cont.


Byte stream classes through reading from and writing to a file: Byte stream classes are used to create and manipulate streams and files for reading and writing bytes. The FileInputStream class allows to read from a file in the form of stream. A stream is a path along which data flows. We can create an object of the class using a File Class and FileOutputStream class allows you to write the output to a file system.
#

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. #

File Input and Output


FileReader/Writer and FileInputStream/OutputStream

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.

File f3=new File(f1,a.java);// it takes f1 and the file


name
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Sequence Input Stream


Sequence Input Stream: This class allows you to concatenate multiple Input streams. SequenceInputStream(input stream1,input stream2); e.g. FileInputStream f1=new FileInputStream(arg[0]); FileInputStream f2=new FileInputStream(arg[1]); SequenceInputStream s=new SequenceInputStream(f1,f2);

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

Network Programming and Java Sockets

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. #

Difference between TCP/IP and UDP


TCP/IP It establish reliable connection between two computers. Data to be send in continuous order. Point to point. e.g. Telephone call Slower The data must be received in the order in which it was send. UDP Unreliable It is to be send packets (datagrams), with less overhead then that for TCP in random order. E.g. letter Faster The order of delivery is random order. Each message is independent of any other.

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

DNS and Port


DNS: DNS is also used to identify the any specific host in the network. It will give either name or 32 bit address 203.26.48.100. Port: data transmitted over the internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by a 32 bit IP address , which IP uses to deliver data to the right computer in the networks.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Internet Applications Serving Local and Remote Users

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. #

Elements of C-S Computing


a client, a server, and network

Client Server Network

Client machine Server machine


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

Networking Basics Cont.


TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers. Example applications: HTTP FTP Telnet

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.

Networking Basics Cont.


UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. Example applications: Clock server Ping

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

Packet port# data


#

TCP or UDP Data


Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

158

Understanding Ports Cont.


Port is represented by a positive (16-bit) integer value Some ports have been reserved to support common/well known services: ftp 21/tcp telnet 23/tcp smtp 25/tcp login 513/tcp User level process/services generally use port number value >= 1024
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

Connection request Client

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

port

159

Socket Communication Cont.


If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client.
port port
Client Connection
# #

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

Input/read stream It can be host_name like mandroo.cs.mu.oz.au

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 Server Cont.


4. Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes("Hello\n"); 5. Close sockets: client.close(); For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with client socket as parameter (the thread creates streams (as in step (3) and does communication as stated in (4). Remove thread once service is provided. }
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

A simple server Cont.


// SimpleServer.java: a simple server program import java.net.*; import java.io.*; public class SimpleServer { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream();
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

A simple server (simplified code)


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. #

A simple client (simplified code)


// SimpleClient.java: a simple client program import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

162

(simplified code) Cont.


String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); } }

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

ServerSocket & Exceptions


public ServerSocket(int port) throws IOException Creates a server socket on a specified port. A port of 0 creates a socket on any free port. You can use getLocalPort() to identify the (assigned) port on which this socket is listening. The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused. Throws: IOException - if an I/O error occurs when opening the socket. SecurityException - if a security manager exists and its checkListen method doesn't allow the operation.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Server in Loop: Always up


// SimpleServerLoop.java: a simple server program that runs forever in a single thread import java.net.*; import java.io.*; public class SimpleServerLoop { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); while(true) { Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket

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

Multithreaded Server: For Serving Multiple Clients Concurrently

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.

Review Questions Cont.


Objective Type Questions
Q.1Exceptions can be caught or rethrown to a calling method. (a) True (b) False Q.2 The subclass exception should precede the base class exception when used within the catch clause. (a) True (b) False Q.3 Can a catch block exist without a try block? (a) Yes (b) No

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

165

Review Questions Cont.


Q.4 Can a finally block exist with a try block but without a catch? (a) Yes (b) No Q.5 Which package contains exception handling related classes? (a) java.lang (b) Java.io (b) java.net java.util
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Review Questions Cont.


Short Type Questions Q.1 What are the different ways to generate and Exception? Q.2 Is it compulsory to use the finally block? Q.3 How are try, catch and finally block organized? Q.4 What is the difference between throw and throws? Q.5 What is the difference between Exception and Error in java?

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions Cont.


Long Questions
Q.1What are Checked Exceptions and Unchecked Exceptions?Explain with Example? Q.2What are User defined Exceptions? Give an Example? Q.3 Write a program to implement thread priority? Q.4 Write a program to implement client-server application? Q.5 Explain java thread life cycle?

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.

Delegation Event Model


Event model is based on the concept of an Event Source and Event Listeners. Any object that generates these messages (or events) is called an Event Source. i.e. a source is an object that generates an event.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

172

Delegation Event Model


A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. The methods that add or remove listeners are provided by the source that generates events.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Delegation Event Model


Any object that is interested in receiving messages (or events ) is called an Event Listener. i.e. A listener is an object that is notified when an event occurs.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Delegation Event Model


It has two major requirements: 1. It must have been registered (add) with one or more sources to receives notifications about specific types of events. 2. It must implement methods to receive and process these notifications.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

173

Delegation Event Model


According to Sun, the reasons for coming out with the Java 1.1 Delegation Event Model are: 1. A source generates an event and sends it to one or more listeners. 2. In this scheme, the listener simply waits until it receives an event. 3. Once received, the listener processes the event and then return.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Delegation Event Model


4. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. 5. A user interface element is able to delegate the processing of an event to a separate piece of code.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Delegation Event Model


6. In this event model, listener must register with a source in order to receive an event notification. This provide an important benefit: notification are sent only to listeners that want to receive them. 7. This is a more efficient way to handle events than the design used by the old java 1.0 approach.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

174

Delegation Event Model


Old java 1.0 approach:- an event was propagated up the containment hierarchy until it was handled by a component. This required components to receive events that they did not process, and it wasted valuable time. Note: The delegation model eliminates this overhead. 8. Facilitate the creation of robust event handling code which is less error-prone (strong compile-time checking)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Methods of component class


Methods of component class1. void setVisible(boolean); 2. void show(); 3. void hide(); 4. void enable(boolean) 5. void disable(boolean) 6. void setSize(int w,int height); 7. void setLocation(int left, int top); 8. void setBounds(int left,int top, int w,int h); 9. Add(object of control)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Steps for creating GUI


Steps for creating GUI: Create object of container Create objects of control Customize appearance of container and controls Add controls on container Show container

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

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

Event Delegation Model is based on four concepts

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.

Event Handling Steps


Listener- Compare and matches the application with its event. Every listener in java is an interface .Hence, need to implement. Steps: 1. Create a Listener class. 2. Give body to all the methods of listener Interfaces. 3. Register the control on which the event is generated. (b.addActionlistner(this))
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Event Handling Steps Cont.


An event listener may be removed from an Event Source's list of interested Listeners by calling a remove...Listener() method, passing in the listener object to be removed. For example, in the above code fragment, the code below removes the action listener object listenerObject from the button m_Button.
m_Button.removeActionListener( listenerObject );
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

Multiple sources, single listener


Many buttons can register the same listener since all buttons generate the same type of event. This type of event may be generated by other types of sources as well.
ActionListener button1 button2 ListItem3

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Single source, multiple listeners


A single source may generate different types of events and thus register multiple listeners.

MouseWheelEvent MouseWheel Listener

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

Single source, multiple listeners again

MouseWheel Listener MouseWheel + MouseMotion Listener MouseMotion Listener

MouseWheelEvent

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Event handling steps


To handle an event you need 3 steps: Implement the appropriate interface that will produce your listener class. Create a listener object. Register the listener to the source of interest.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Putting it into code


You register a listener using corresponding add function in the form:
component.addSomeListener(listener_object);

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

Listeners for Each Event


Event
ActionEvent AdjustmentEvent ComponentEvent

Listener
ActionListener AdjustmentListener ComponentListener

Method
actionPerformed() adjustmentValueChangd() componentResized() componentMoved() componentShown() componentHidden() focusGained() focusLost() itemStateChanged() keyTyped() keyPressed() keyReleased()

FocusEvent ItemEvent KeyEvent

FocusListener ItemListener KeyListener

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Listeners for Each Event


MouseEvent MouseListener mouseClicked() mouseEntered() mouseExited() mousePressed() mouseReleased() mouseDragged() mouseMoved() WindowEvent WindowListener windowClosed() windowClosing() windowDeiconified() windowIconified() windowOpened()

MouseMotionListener

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Listeners for Object


The following table lists which objects can have which listener types added: GUI Object Button Choice Checkbox Component Listener ActionListener ItemListener ItemListener ComponentListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener
#

Dialog

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

182

Listeners for Each Event


Frame List MenuItem Scrollbar TextField WindowListener ActionListener,ItemListener ActionListener AdjustmentListener ActionListener

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.

Adapter classes Cont.


Adapter classes are fully abstract classes that correspond to listener interfaces. They are extended (not implemented) and thus you can ignore methods that do not interest you. You can use them instead of listeners in the case that only some of the methods of the interface are to be used.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

184

Adapter classes Cont.


You dont use the abstract specifier and of course you cannot use multiple inheritance. Some adapter classes: KeyAdapter (instead of KeyListener) MouseAdapter (MouseListener) MouseMotionAdapter (MouseMotionListener) etc

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Adapter classes Cont.


Event listeners often define many methods. Since they are interface, you must implement all of them. Alternative: Subclass an appropriate adapter and override only the one you need.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Adapter classes Cont.


Adapter Classes

Adapter Class ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindoAdapter

Listener Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener


#

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

185

Adapter classes Cont.


import java.applet.*; import java.awt.*; import java.awt.event.*; public class MouseAdapterDemo extends Applet { public void init() { setBackground(Color.green); addMouseListener(new MyMouseAdapter(this)); }}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Adapter classes Cont.


class MyMouseAdapter extends MouseAdapter { MouseAdapterDemo mad; public MyMouseAdapter(MouseAdapterDemo mad) { this.mad = mad; } public void mousePressed(MouseEvent me) { mad.setBackground(Color.red); mad.repaint(); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Adapter classes Cont.


public void mouseReleased(MouseEvent me) { mad.setBackground(Color.green); mad.repaint(); } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

186

Methods of event Handling


There are three methods of event handling:1. Outer class 2. Inner class 3. Same class

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.

Inner Classes Cont.


public void init() { setBackground(Color.green); addMouseListener(new MyMouseAdapter()); } class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) { setBackground(Color.red); repaint();} public void mouseReleased(MouseEvent me) { setBackground(Color.green); repaint();} }}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Anonymous Inner Classes


import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="MouseAnonymousDemo" width=100 height=100> </applet> */ public class MouseAnonymousDemo extends Applet { public void init() { setBackground(Color.green); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { setBackground(Color.red); repaint(); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

188

Anonymous Inner Classes Cont.


public void mouseReleased(MouseEvent me) { setBackground(Color.green); repaint(); } }); An Anonymous Inner Class } }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Console vs. GUI applications


What is the difference between a GUI and a console app? From the programmers perspective? A console app enables interaction through a specified flow of I/Os. A GUI app makes it much more flexible. The user is allowed to perform combinations of actions.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with Windows


Class Frame java.lang.Object java.awt.Component java.awt.Container java.awt.Window java.awt.Frame
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

189

Working with Frame Windows Cont.


A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method, however, since these dimensions are platform-dependent, a valid insets value cannot be obtained until the frame is made displayable by either calling pack or show. Since the border area is included in the overall size of the frame, the
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Working with Frame Windows Cont.


border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom). The default BorderLayout. layout for a frame is

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with Frame Windows Cont.


Frame() //creates a standard window that does not contain a title. Frame(String title) //creates a window with the title specified by title. Methods Setting the windows dimension void setSize(int w,int h); Hiding and Showing a window setVisible(boolean flag) Setting a window title void setTitle(String str) Closing a frame window setVisible(false)

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.

Working with Frame Windows


TextField- is a control used for single line input. 1. TextField() 2. TextFieldl(String) setText() & getText()

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

191

Working with Frame Windows


Button Button b=new Button(ok) Method b.setLabel(String) b.getLabel(String)

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with Windows


e.g. Button 1.EventName -ActionEvent getSource()-generate reference of event object. 2.Listener -ActionListener Method is public void actionPerformed(ActionEvent e) 3.To Register -addActionListener

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with Graphics


java.lang.Object java.awt.Graphics public abstract class Graphics extends Object The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices, as well as onto offscreen images. (public class Object Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.)
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 Lines Example


import java.awt.*; import java.applet.*; public class Lines extends Applet { public void paint(Graphics g) { g.drawLine(40,25,250,180); g.drawLine(75,90,400,400); } }
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

Drawing Rectangles Cont.


fillRect public abstract void fillRect(int x, int y, int width, int height) Fills the specified rectangle. The left and right edges of the rectangle are at x and x + width - 1. The top and bottom edges are at y and y + height - 1. The resulting rectangle covers an area width pixels wide by height pixels tall. The rectangle is filled using the graphics context's current color. Parameters: x - the x coordinate of the rectangle to be filled. y - the y coordinate of the rectangle to be filled. width - the width of the rectangle to be filled. height - the height of the rectangle to be filled.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Drawing Rectangle Example


import java.awt.*; import java.applet.*; public class Lines extends Applet { public void paint(Graphics g) { g.drawRect(10,10,60,50); g.fillRect(100,10,60,50); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Drawing Rounded Rectangle


drawRoundRect public abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color. The left and right edges of the rectangle are at x and x + width, respectively. The top and bottom edges of the rectangle are at y and y + height. 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. arcWidth - the horizontal diameter of the arc at the four corners. arcHeight - the vertical diameter of the arc at the four corners.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

194

Drawing Rounded Rectangle Cont.


fillRoundRect public abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Fills the specified rounded corner rectangle with the current color. The left and right edges of the rectangle are at x and x + width - 1, respectively. The top and bottom edges of the rectangle are at y and y + height - 1. Parameters:
x - the x coordinate of the rectangle to be filled. y - the y coordinate of the rectangle to be filled. width - the width of the rectangle to be filled. height - the height of the rectangle to be filled.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Drawing Rounded Rectangle Example.


import java.awt.*; import java.applet.*; public class Lines extends Applet { public void paint(Graphics g) { g.drawRoundRect(190,10,60,50,15,15); g.fillRoundRect(70,90,140,100,30,40); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Drawing Oval Example.


drawOval public abstract void drawOval(int x, int y, int width, int height)
Draws the outline of an oval. The result is a circle or ellipse that fits within the rectangle specified by the x, y, width, and height arguments. The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall. Parameters:
x - the x coordinate of the upper left corner of the oval to be drawn. y - the y coordinate of the upper left corner of the oval to be drawn. width - the width of the oval to be drawn. height - the height of the oval to be drawn.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

195

Fill Oval Example


fillOval public abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color. Parameters:
x - the x coordinate of the upper left corner of the oval to be filled. y - the y coordinate of the upper left corner of the oval to be filled. width - the width of the oval to be filled. height - the height of the oval to be filled.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Draw Arc Example


drawArc public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws the outline of a circular or elliptical arc covering the specified rectangle. The resulting arc begins at startAngle and extends for arcAngle degrees, using the current color. Angles are interpreted such that 0 degrees is at the 3 o'clock position. A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation. The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments. The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Draw Arc Example Cont.


The angles are specified relative to the non-square extents of the bounding rectangle such that 45 degrees always falls on the line from the center of the ellipse to the upper right corner of the bounding rectangle. As a result, if the bounding rectangle is noticeably longer in one axis than the other, the angles to the start and end of the arc segment will be skewed farther along the longer axis of the bounds.
Parameters: x - the x coordinate of the upper-left corner of the arc to be drawn. y - the y coordinate of the upper-left corner of the arc to be drawn. width - the width of the arc to be drawn. height - the height of the arc to be drawn. startAngle - the beginning angle. arcAngle - the angular extent of the arc, relative to the start angle.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

196

Fill Arc Example Cont.


fillArc public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills a circular or elliptical arc covering the specified rectangle. The resulting arc begins at startAngle and extends for arcAngle degrees. Angles are interpreted such that 0 degrees is at the 3 o'clock position. A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation. The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments. The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Fill Arc Example Cont.


The angles are specified relative to the non-square extents of the bounding rectangle such that 45 degrees always falls on the line from the center of the ellipse to the upper right corner of the bounding rectangle. As a result, if the bounding rectangle is noticeably longer in one axis than the other, the angles to the start and end of the arc segment will be skewed farther along the longer axis of the bounds.
Parameters: x - the x coordinate of the upper-left corner of the arc to be filled. y - the y coordinate of the upper-left corner of the arc to be filled. width - the width of the arc to be filled. height - the height of the arc to be filled. startAngle - the beginning angle. arcAngle - the angular extent of the arc, relative to the start angle.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Draw String Example


drawString public abstract void drawString(String str, int x, int y)
Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system. Parameters:
str - the string to be drawn. x - the x coordinate. y - the y coordinate. Etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

197

Draw String Example Cont


Text strings You already met the instruction used to display strings on the screen. In case you didn't, you won't be surprised to hear that it is drawString. Just to remind you - a string is a piece of text, anything from a single character (a term which includes letters, punctuation, symbols such as @ or ^, and even the space character) to a whole sentence. Strings are specified by placing them within double quotation marks.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Draw String Example Cont


The method drawString is given three parameters between brackets. The first item is the string itself to be displayed on the screen. The other two numbers specify where the string is to appear. It represents the top-left corner of the string. However, the second number actually specifies the y-co-ordinate of a line on which the text sits. Some characters, such as 'g' or 'y' will drop down below this imaginary line, as shown in the following example: g.drawString("This is hugely easy",40,60);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Working with colors


If you don't specify a colour for drawing shapes or text, then Java uses the default colour of black. Specifying a colour is fairly easy - although you can only specify one of 13 standard colours (including white). There is a standard method built into graphics environment variables called setColor (note the

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

198

Working with colors Cont.


American spelling of 'Color'). It expects to be given a colour name, but the colour name must be of a standard type specified in yet another class called Color. What all this means is that colours are chosen as follows: g.setColor(Color.blue); g.setColor(Color.orange);

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with colors Cont.


Here are the thirteen standard colours. Make sure you use them exactly as specified don't alter the case of the letters or insert spaces in the middle of them, and note the spelling of 'Gray'.
Black Green darkGray Gray Pink Magenta Orange Cyan white Yellow lightGray Blue Red

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with colors Cont.


Any colour that you choose will then be used for drawing all lines, text, shapes and as the fill-in colour for shapes until you choose another colour. You can also determine the colour of the background to the applet. This is done using the following instruction: setBackground(Color.cyan); Again, like the setColor method, it is important to note that the name of the method is all lower case letters except for the
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

199

Working with colors Cont.


capital B in the middle. However, please note that setBackground is not part of the graphics environment, and as such, does not need to be preceded by g. In fact, if you do put g. at the beginning, then the Java compiler complains. I have fallen into this trap many times!

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with repaint()


repaint Occasionally, there will be points in the program where you will want it redraw the screen. Perhaps the screen has changed (the paint method can easily cope with if statements that get it to draw different things in different circumstances). To call the paint method in these circumstances, use the following instruction:

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Working with repaint()0.


repaint(); Note that there are no parameters (no numbers, strings or graphics environments) passed to this method, but you still must include the two brackets and follow them with the obligatory semicolon, like this (); It is vital that you don't include this method inside the paint method itself. If you did, the paint method would never terminate, as it would always be calling itself.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

200

Using AWT Controls


Controls are components that allows a user to interact with your application in various ways- e.g. a commonly used control is the push button. The AWT supports the following types of controls: Lables Push buttons Check boxes Choice lists Lists Scroll bars Text editing These controls are subclass of Component.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Using AWT Controls Cont.


Adding and Removing Controls To include a control in a window, you must add it to the window by using add() method, which is defined by container. Componenet add(Componenet compobj) Compobj=is an instance of the control that you want to add.a reference to compobjc is returned. Once a control has been added it will automatically be visible whenever its parent window is displayed. void remove(Componenet obj) and removeAll() are used.// to remove control from a window
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Using AWT Controls Cont.


Responding to controls Except for Labels, which are passive controls, all controls generate events when they are accessed by the user. Labels A label is an object of type Label. Label() Label(String str) Label(String str, int how)
Where Label.LEFT, Label.RIGHT, Label.CENTER

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

201

Using AWT Controls Cont.


Buttons A push button is a componenet that contains a label and that generates an event when it is pressed. These are objects of type Button. Button() Button(String str)

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Using AWT Controls Cont.


Choice and List
Event- ItemEvent Listener- ItemListener Method- public void ItemStateChanged(ItemEvent e) Register- addItemListener(ItemListener)

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Using AWT Controls Cont.


Scrollbar (horizontal/vertical)
Event- AdjustmentEvent Listener- AdjustmentListener Method- public void AdjustmentValueChanged(AdjustmentEvent e) Register- addAdjustmentListener(ItemListener)

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

202

Using AWT Controls Cont.


CheckBox- Multiple Selection checkBox(String) e.g. checkBox c=new CheckBox(string); checkBox(string,Boolean) e.g. checkBox c1=new CheckBox(study,true);

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Using AWT Controls Cont.


RadioButton- Single Selection
checkBox(String,Boolean,CheckBoxGroupobject) e.g. checkBoxGroup cg=new CheckBoxGroup(string); checkBox c=new CheckBox(Male,true,cg); e.g. checkBox c1=new CheckBox(Female,false,cg);

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.

Layout Managers Code


Putting it into code: Setting the manager: Container myCont = getContentPane(); myCont.setLayout(new FlowLayout()); Adding Components: myCont.add(aComponent, BorderLayout.WEST);

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.

Handling Image Cont.


The Image class provides only minimal access to information about the image. It does include the methods int getWidth (ImageObserver) int getHeight (ImageObserver) that return the dimensions of an image. You can draw on an image just as you would draw on a component by obtaining the graphics context object via the Image class method Graphics getGraphics () You then invoke the usual drawing methods in the Graphics object to draw on the image.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Handling Image Cont.


You can create an image just to draw on it using the createImage() method from the Component class as in the following snippet: Image image = createImage (width, height); Graphics g = image.getGraphics (); paint (g); // Your paint() method does the usual drawing
operations // but on the image rather than on a component.

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

Sound And Video


The Java Media Framework API (JMF) enables audio, video and other time-based media to be added to applications and applets built on Java technology. This optional package, which can capture, playback, stream, and transcode multiple media formats, extends the Java 2 Platform, Standard Edition (J2SE) for multimedia developers by providing a powerful toolkit to develop scalable, cross-platform technology.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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

APPLET Life Cycle


Applet lifecycle: (methods overridden from Applet class): init(), start(), paint(g),stop(), destroy() Loading an applet an instance of the applets controlling class (Applet subclass) created applet initializes itself applet starts running

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

APPLET Life Cycle Cont.


Leaving and returning to applet page when page is left, applet stops upon page return, applet starts Applet reloading/unloading applet performs final cleanup, before reloading Browser quitting - (applet stops, performs final cleanup)

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. #

Creating a frame by usingSwing


import javax.swing.*; public class Swing_Create_Frame{ public static void main(String[] args) {JFrame frame = new JFrame("Frame in Java Swing"); frame.setSize(400, 400); frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} }

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

OR Creating a frame by using Swing


import javax.swing.JFrame; public class Simple extends JFrame { public Simple() { setSize(300, 200); setTitle("Simple"); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { Simple simple = new Simple(); simple.setVisible(true); } }
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.

Servlet Cycle Cont.


(Service Method) On each request, the server spawns a new thread and calls service() service() checks HTTP request type and calls appropriate doXXXX (Get, Post, Put...) don't override service (unless you really know what you're doing)

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.

Review Questions Cont.


Q3)Which of the following are direct or indirect subclasses of container (a)Frame (b)TextArea MenuBar (d)FileDialog (e)Applet Q4)Which method will cause a frame to be displayed (a)show() (b)setVisible() display() (d)DisplayFrame()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

219

Review Questions Cont.


Q5)Which method is method to set the layout of a container startLayout() initLayout() layoutContainer() setLayout()

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions Cont.


Short Questions
Q1)What is the difference between JDBC and ODBC? Q2)What are the types of JDBC Driver Models and explain them?Q3)What is source and listener?Q4)What is adapter class?Q5)What is meant by controls and what are different types of controls in AWT?Q6)What is the difference between choice and list?Q7)What is the difference between scrollbar and scrollpane? Q8)What is an event and what are the models available for event handling?
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Review Questions Cont.


Long Questions
Q1)What are the steps involved for making a connection with a database or how do you connect to a database? Q2)What is the difference between applications and applets?Q3)How are the elements of different layouts organized Q4)What are the advantages of the even delegation model over the event-inheritance model? Q5)What is a layout manager and what are different types of layout managers available in java AWT?

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.

Overview of Internet and Intranet Services

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

Overview of Internet and Intranet Services Cont.

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.

Overview of Internet and Intranet Services Cont.

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.

Advantage & Disadvantage


Advantages : Communication Information Entertainment Services (online banking, job seeking, purchasing tickets for your favorite movies, guidance services, etc. ) E-Commerce (business deals, that involves the transfer of information across the globe via Internet ),etc.

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. #

Static page Cont.


Disadvantages Difficult to maintain when a site gets large. Difficult to keep consistent and up to date. Offers little visitor personalization (all would have to be client side

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

Dynamic page Cont.


Scripts can read in data sources and display it differently depending on how it is run. Can create the illusion of being updated regularly using time and date sensitive routines (or even randomizers) to display pre-written text.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Dynamic page Cont.


Disadvantages Personalized pages are not very cache friendly. Requires a basic minimum knowledge of the language being used. Scripts need more consideration when uploading and installing, particularly to *nix servers.

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

HTML Tag EXAMPLE


<html> <head> <title>Title of page</title> </head> <body> This is my first homepage. <b>This text is bold</b> </body> </html> Note: Save this file as firstpage.htm".

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

HTML Tag Cont.


HTM or HTML Extension? When you save an HTML file, you can use either the .htm or the .html extension. We have used .htm in our examples. With newer software we think it will be perfectly safe to use .html.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

HTML Tag Cont.


HTML documents are text files made up of HTML elements. HTML elements are defined using HTML tags. HTML Tags HTML tags are used to mark-up HTML elements HTML tags are surrounded by the two characters < and > The surrounding characters are called angle brackets
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

226

HTML Tag Cont.


HTML tags normally come in pairs like <b> and </b> The first tag in a pair is the start tag, the second tag is the end tag The text between the start and end tags is the element content HTML tags are not case sensitive, <b> means the same as <B>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

HTML Tag Cont.


Headings Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading. <h6> defines the smallest heading.
<h1>This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3> <h4>This is a heading</h4> <h5>This is a heading</h5> <h6>This is a heading</h6>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

HTML Tag Cont.


HTML automatically adds an extra blank line before and after a heading. Paragraphs Paragraphs are defined with the <p> tag. <p>This is a paragraph</p> <p>This is another paragraph</p> HTML automatically adds an extra blank line before and after a paragraph.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

227

HTML Tag Cont.


HTML Tag Attributes HTML tags can have attributes. Attributes provide additional information to an HTML element. Attributes always come in name/value pairs like this: name="value". Attributes are always specified in the start tag of an HTML element.

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. #

Formatted Text Cont.


This text is big </small><br> <em> This text is emphasized </em> <br> </html>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

228

Formatted Text Cont.


<i> This text is italic </i> <br> <small> This text is small </small> <br> This text contains

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Formatted Text Cont.


<sub> subscript </sub> <br> This text contains <sup> superscript </sup> </body>
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. #

Font Tag Cont.


<html> <body bgcolor=#111111> <pre><font color="#FFFFFF"> This is preformatted text. It preserves both spaces and line breaks. </FONT> </pre>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

232

Font Tag Cont.


<p ><font color="#FFFFFF">The pre tag is good for displaying computer code:</FONT></p> <pre><font color="#FFFFFF"> for i = 1 to 20 print i next i </font> </pre> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Font Tag Cont.


The following is an example of some of the COLOR codes (Hexadecimal Codes) that will be used with the COLOR parameter in a <font> tag.
Color Red Turquoise Light Blue Dark Blue Light Purple Dark Purple Yellow Pastel Green Pink Color code #FF0000 #00FFFF #0000FF #0000A0 #FF0080 /pre> #FFFF00 #00FF00 #FF00FF
#

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Font Tag Cont.


Color White Light Grey Dark Grey Black Orange Brown Burgundy Forest Green Grass Green Color code #FFFFFF #FFFFCC hite lack #FF8040 rown rown rown rown
#

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. #

Table Example Cont.


<tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table></body> </html>

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.

Table Attributes Cont.


ALIGN=[ left | center | right ] (table alignment) BGCOLOR=Color (table background color) Length Length attribute values may be either an integer--interpreted as a number of pixel. or a percentage of the horizontal or vertical space. The value 50% means half the available space while 50 means 50 pixels.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Table EXample Cont.


<html> <head> <title>This is a table</title> <body> <TABLE bgcolor=green ALIGN=CENTER WIDTH="80%" BORDER=1 CELLSPACING=5 CELLPADDING=3> <CAPTION>The Nordic countries</CAPTION> <TR> <TD>Denmark</TD> <TD>Finland </TD>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

235

Table Example Cont.


<TD>Iceland </TD> <TD>Norway </TD> <TD>Sweden </TD> </TR> </TABLE> </body> </html>

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

Definition Lists Example


<dd>White cold drink</dd> </dl> Here is how it looks in a browser: Coffee Black hot drink Milk White cold drink

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Definition Lists Example Cont.


<dl> <dt>Coffee</dt> <dd><ol><li>Black hot drink</li> <li>normal drink</li></ol></dd> <dt>Milk</t> <dd><ol><li>White cold drink</li> <li>Another drink</li></ol></dd> </dl> Coffee 1. Black hot drink 2. normal drink Milk 1. White cold drink 2. Another drink
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. #

Forms Example Cont.


Password Fields <html> <body> <form action=""> Username: <input type="text" name="user"> <br> Password: <input type="password" name="password > </form>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Forms Example Cont.


<p> Note that when you type characters in a password field, the browser displays asterisks or bullets instead of the characters. </p> </body> </html>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

243

Forms Example Cont.


The Image Tag and the Src Attribute
In HTML, images are defined with the <img> tag. The <img> tag is empty, which means that it contains attributes only and it has no closing tag. To display an image on a page, you need to use the src attribute. Src stands for "source". The value of the src attribute is the URL of the image you want to display on your page. The syntax of defining an image: <img src="url">
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Forms Example Cont.


<html> <body> <p> An image: <img src="constr4.gif" width="144" height="50"> </p> <p> A moving image: <img src="hackanm.gif" width="48" height="48"> </p>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Forms Example Cont.


<p> Note that the syntax of inserting a moving image is no different from that of a nonmoving image.</p> </body> </html>

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

Background and text color


<html> <body bgcolor="#ffffee" text="red"> <p> This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. </p> <p> This is another paragraph. This is another paragraph. This is another paragraph. This is another paragraph. </p> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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. #

Radio Button Example


<input type="radio" name="sex" value="female"> Female </form> </html> Note: Only one option can be chosen.

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:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="checkbox" name="vehicle" value="Bike">

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Checkbox Example Cont.


<br> car:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbs p&nbsp <input type="checkbox" name="vehicle" value="Car"> <br> airplane: <input type="checkbox" name="vehicle" value="Airplane"> </form></html>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

The Form's Action Attribute and the Submit Button

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

The Form's Action Attribute and the Submit Button

Username: <input type="text" name="user"> <br><br><br><br> <input type="Button" value="OK"> &nbsp&nbsp&nbsp&nbsp <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. #

Dropdown List Example


<html> <body> <form action=""> <select name="country"> <option value="india">india</option> <option value="pakistan">pakistan</option> <option value="america" selected="selected">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.

Static web sites


Static Web Sites For a static-content Web site, all content appearing on Web pages is placed manually by professional Web developers. This is also called "design-time page construction," because the pages are fully built while the site is being developed. Static-content Web site is developed and then maintained by experienced professionals.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Static web sites Cont.


Such Web site usually costs less when initially developed, but then all future changes still have to be done by Web professionals. Therefore a static Web site can be more expensive to maintain, especially when you want to make frequent changes to your site

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

252

Dynamic web sites


Dynamic Web Sites On the other hand, pages in a dynamiccontent Web site are constructed "on the fly" when a page is requested from a Web browser. Dynamic-content Web site, while still developed by professionals, can be maintained directly by you, our customer. Such Web site initially costs more to develop,
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Dynamic web sites Cont.


but then you don't have to pay Web professionals every time you need to change something on your site. If you plan to make frequent changes to your site, you most likely will be better off with a dynamic Web site.

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.

Install IIS and run ASP


How to install IIS and run ASP on Windows 2000 1. From your Start Button, go to Settings, and Control Panel 2. In the Control Panel window select Add/Remove Programs 3. In the Add/Remove window select Add/Remove Windows Components 4. In the Wizard window check Internet Information Services, click OK 5. An Inetpub folder will be created on your harddrive .
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

257

Install IIS and run ASP Cont.


6. Open the Inetpub folder, and find a folder named wwwroot Create a new folder, like "MyWeb", under wwwroot. Use a text editor to write some ASP code, save the file as "test1.asp" in the "MyWeb" folder

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Install IIS and run ASP Cont.


Make sure your Web server is running - The installation program has added a new icon on your task bar (this is the IIS symbol). Click on the icon and press the Start button in the window that appears. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view your first ASP page

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

Add html tag to the text in ASP File


<html> <body> <% response.write("<h2>You can use HTML tags to format the text!</h2>") %> <% response.write("<p style='color:#0000ff'>This text is styled with the style attribute!</p>") %> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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. #

A form with method="get"


<html> <body> <form action="demo_reqquery.asp" method="get"> First name: <input type="text" name="fname" size="20" /> Last name: <input type="text" name=lname" size="20" /> <input type="submit" value="Submit" /></form>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

259

A form with method="get"


<% dim fname,lname1 fname1=Request.QueryString("fname") lname1=Request.QueryString(lname") 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. #

A form with method="get" Cont.


<html> <body> <form action=output.asp" method="get"> First name: <input type="text" name="fname" size="20" /> Last name: <input type="text" name="lname" size="20" /> <input type=Button" value=ok" /></form> <input type="submit" value="Submit" /></form> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

A form with method=get Cont.


<% dim a,b a=Request.QueryString("fname") b=Request.QueryString("lname") If a<>"" Then Response.Write("Hello " & a & "!<br />") response.write("How are you today?") End If %>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

260

A form with method=get Cont.


User Input The Request object may be used to retrieve user information from forms. Form example: <form method="get" action="simpleform.asp"> First Name: <input type="text" name="fname" /><br > Last Name: <input type="text" name="lname" /><br
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

A form with method=get Cont.


<input type="submit" value="Submit" /></form> User input can be retrieved in two ways: With Request.QueryString or Request.Form.

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

A form with method=get Cont.


Assume that the ASP file "simpleform.asp" contains the following script: <body> Welcome <% response.write(request.querystring("fname")) response.write(" " & request.querystring("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. #

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. #

A form with method post


A form with method="post <html> <body> <form action="demo_simpleform.asp" method="post"> Your name: <input type="text" name="fname" size="20" /> <input type="submit" value="Submit" /> </form>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

262

A form with method post Cont.


<% 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.

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. #

radio button example


<%if cars="Volvo" then Response.Write("checked")%> value="Volvo">Volvo</input><br /> <input type="radio" name="cars" <%if cars="Saab" then Response.Write("checked")%> value="Saab">Saab</input> <br />

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

263

radio button example


<input type="radio" name="cars" <%if cars="BMW" then Response.Write("checked")%> value="BMW">BMW</input> <br /><br /> <input type="submit" value="Submit" /> </form> <% if cars<>"" then Response.Write("<p>Your favorite car is: " & cars & "</p>") end if %> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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.

Another Application Cont.


<html> <body> <p> <b>You are browsing this site with:</b> <%Response.Write(Request.ServerVariables ("http_user_agent"))%> </p> <p> <b>Your IP address is:</b> <%Response.Write(Request.ServerVariables ("remote_addr"))%> </p> <p>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

265

Another Application Cont.


<b>The DNS lookup of the IP address is:</b> <%Response.Write(Request.ServerVariables ("remote_host"))%> </p> <p> <b>The method used to call the page:</b> <%Response.Write(Request.ServerVariables ("request_method"))%></p>

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Another Application Cont.


<p> <b>The server's domain name:</b> <%Response.Write(Request.ServerVariables ("server_name"))%> </p> <p> <b>The server's port:</b> <%Response.Write(Request.ServerVariables ("server_port"))%> </p> <p> <b>The server's software:</b>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Another Application Cont.


<%Response.Write(Request.ServerVariables(" server_software"))%> </p> </body> </html>

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. #

Server Object Cont.


Set objConnection = Server.CreateObject(ADODB.Connection) The only parameter that the CreateObject takes (ADODB.Connection in the above example) specifies the type of object to be created. The Server.CreateObject doesnt have a return value. executes an ASP page as a part of the parent (calling) ASP page.
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

Connection String Example


<% dim name,cre,total,conn,sql name="Divya" cre="0123456" total="2000" dat="12-Mar-2008" set conn=server.createobject("ADODB.connectio n") conn.open "DSN=man"
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Connection String Example


sql="insert into shop(name,cre,amount,dat) values('"&name&"','"&cre&"','"&total&"','"&dat &"')" conn.execute sql %> <Html> <Body> <H1>Data is Stored in Data Base</H1> </Body> <Html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

Another Connection String Example


<html> <body> <center> <table border=1> <tr bgcolor="lightblue"><th colspan="4">Men's Wear Details</th></tr> <tr><th bgcolor="#FFFFCC">Date of Order</th><th bgcolor="#FFFFCC">Credit Card Number</th> <th bgcolor="#FFFFCC">Custormer Name</th><th bgcolor="#FFFFCC">Amount of Purchase (Rs.)</th></tr>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

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")%>&nbsp;</td><td > <%=rec.fields("cre")%>&nbsp;</td><td><%=re c.fields("name")%>&nbsp;</td><td><%=rec.fi elds("amount")%>&nbsp;</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.
#

onChange onClick onDblClick onFocus onKeydown onKeyup onKeypress

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

270

JavaScript Event Cont.


onLoad onMoused own onMouseu p onMouseo ver onMousem ove onMouseo ut onReset The object has loaded. The cursor moved over the object and mouse/pointing device was pressed down. The mouse/pointing device was released after being pressed down. The cursor moved over the object (i.e. user hovers the mouse over the object). The cursor moved while hovering over an object. The cursor moved off the object User has reset a form.
#

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

JavaScript Event Cont.


onSelect User selected some or all of the contents of the object. For example, the user selected some text within a text field. User submitted a form. User left the window (i.e. user closes the browser window). The object has loaded.

onSubmit onUnload onLoad

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. #

JavaScript Event Cont.


onMousem The cursor moved while hovering over an object. ove onMouseou The cursor moved off the object t onReset User has reset a form. onSelect User selected some or all of the contents of the object. For example, the user selected some text within a text field. User submitted a form. User left the window (i.e. user closes the browser window).
#

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

Review Questions Cont.


Q3)Which command we use to link a page with an HTML page? a. <a link=\"page.htm\" ></a> b. <a href=\"page.htm\"?phpMyAdmin=70ac9566533a2665b6597346aab7f9 85 ></a> c. <a connect=\"page.htm\" ></a> d. <a attach=\"page.htm\" ></a> Q4) Java is different from JavaScipt a) True b) False Q5)JavaScript is a server side scripting. a) True b) False

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions Cont.


Short Questions Q1)How Cell Padding is differ from Cell Spacing? Q2)How you define HEAD in HTML? Q3)How you define SPAN in HTML? Q4)What are basic HTML tags how we use them? Q5)Can we write a comment into the HTML? Q6)How to use Line Break and Horizontal Line tags in HTML? Q7)How many types of cookies are available in asp? Q8)What is ServerVariables collection?

Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.

Review Questions Cont.


Long Questions Q1)Explain the POST & GET Method or Explain the difference between them? Q2)What is the difference between Server-side validation and Client-side validation? Q3)What is the difference between Querystring collection and Form collection? Q4)How are sessions maintained? Q5)Explain to implement a connection string? Q6)how can i connect to ms-access database, with ASP?
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

Das könnte Ihnen auch gefallen