ipu java notes

274
1 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63 ‹#› UNIT-1 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#› • 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 Learning Objectives © Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#› 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 Obtaining the Java SDK

Upload: manoj-kumar-jawlia

Post on 28-Oct-2014

298 views

Category:

Documents


17 download

TRANSCRIPT

Page 1: Ipu Java Notes

1

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63 ‹#›

UNIT-1

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Obtaining the Java SDK

• Java Version History

• Importance and features of Java

• JVM

• How to write and run Java Applicationprograms

• Java Interface to achieve multiple inheritance

• Putting classes together by using package

Learning Objectives

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Obtaining the Java SDK

Page 2: Ipu Java Notes

2

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• tar or self extracting file for SPARC

• To install, execute the installer program or extract from tar file.

Obtaining the Java SDK

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Java Version History

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

-Addition of Swing GUI (Mostly replacesAWT)

-Improved Security-Enterprise computing.• Java 1.3 (2000)

- Many extended APIs added- Improved performance

• Java 1.4(2002)-Improved performance-Bug Fixes.etc.

Java Version History

Page 3: Ipu Java Notes

3

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

The Java Software Development Kit

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java is an object-oriented programminglanguage with a built-in applicationprogramming interface (API) that canhandle graphics and user interfaces andthat can be used to create applications orapplets. Because of its rich set of API's,similar to Macintosh and Windows, and itsplatform independence, Java can also bethought of as a platform in itself. Java alsohas standard libraries for doingmathematics.

Introduction to Java

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Much of the syntax of Java is the same as Cand C++. One major difference is that Javadoes not have pointers. However, thebiggest difference is that you must writeobject oriented code in Java. Proceduralpieces of code can only be embedded inobjects. In the following we assume that thereader has some familiarity with aprogramming language. In particular, somefamiliarity with the syntax of C/C++ is useful.

Introduction to Java Cont.

Page 4: Ipu Java Notes

4

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• In Java we distinguish between applications,which are programs that perform the samefunctions as those written in otherprogramming languages, and applets, whichare programs that can be embedded in aWeb page and accessed over the Internet.Our initial focus will be on writingapplications. When a program is compiled, abyte code is produced that can be read andexecuted by any platform that can run Java.

Introduction to Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• It is an object- oriented languagedeveloped by Sun in the mid 1990s.-Original language called Oak (renamedJava 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

Importance and Features of Java

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• simple

• object- oriented

• distributed

• interpreted

• robust

• secure

• architect neutral

• Portable

• high-performance

Features of Java

Page 5: Ipu Java Notes

5

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• multi- threaded, and• dynamic language

Object Oriented-Designed to support object-oriented

conceptsOOPs is a programming that helps toorganize complex programs through theuse of inheritance, polymorphism andencapsulation.

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Distributed

-Applications are constructed using objects.Objects can be distributed in multiplelocations within a network environment..

-This allowed objects on two differentcomputers to execute procedures remotelyby using RMI (Remote Method Invocation).

Features of Java Cont.

Page 6: Ipu Java Notes

6

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

-Extensive integration with TCP/IP

• Java have extensive library of routines forcopying TCP/IP

Protocols like HTTP,FTP.

- Java application can open and accessobjects across the Net via URL’S as thesame case as when accessing a local file.

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java provides a “firewall” between a networkapplication and compiler.

• Java Compatible browsers can safelydownloaded, java applet with fear of virtualinfection or malicious intent like (private infoas credit card number, bank accountbalance, password ) by searching the contentof computer local file system.

How Java is Secure

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java achieves protection by confiningjava programs to java environment andnot allowing it to access to other parts ofcomputer.

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.

Features of Java Cont.

Page 7: Ipu Java Notes

7

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The compiler generates an architecture neutralobject file format-the compiled code can run onmany processors (8085,8086,386 etc.) give thepresence of java runtime system.

Portable( different kind of O/S)• The java compiler does this by generating

byte code instructions which have nodependency on computer architecturerather they are designed to be easy tointerpret on any machine and easilytranslated to native machine code

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Many database servers, Applicationservers, Web servers and web browserscontain a JVM.

e.g. Oracle, Tomcat (Web Server),WebSphere (App server), BEA Weblogic(App server), Netscape and IE etc.

High – Performance

• Speed

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Features of Java Cont.

Page 8: Ipu Java Notes

8

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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 orregister user.

- A security manager can limit access toresources such as the local files or the network.

-Any unreferenced memory are returned to thesystem by Garbage collector thread.

Java VM Responsibility

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java source files (.java) are compiled to Java byte code (.class)

• Bytecode is interpreted on the target plateform within a Java Virtual Machine

Source .java Java Compiler Java Bytecode Source. class

PPC VM

SPARC VM

i386VM

JVM

Page 9: Ipu Java Notes

9

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Traditionally, source code had to becompiled for the target hardware and OSplateform.

Windows Compiler

-i386 binary

Solaries Compiler

-SPARC binary

Mac Compiler

-PPC binary

JVM Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

.

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

-Instead JIT compiles as it is needed duringexecution.

-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 areerror prone.

-It eliminate the overwriting memory andcorrupting data ( mishandled exceptioncode like divide by zero)

Features of Java Cont.

Page 10: Ipu Java Notes

10

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Secure

-All java code subject to security model.

-java enables construction of virus free, temper free system.

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Features of Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

-Inter-process communication expensive(Inter Process Communication is acapability that allows one process tocommunicate 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).

Features of Java Cont.

Page 11: Ipu Java Notes

11

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Applications, Applets & Servlet

JavaJava programsprograms areare ofof threethree typestypes::1.Applications§ a standalone program§ executed from the operating system

environment2.Applets§ a short program designed to be

incorporated within a Web document§ executed using a Web browser

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

3.Servlets

§ It is a server side program similar to anapplet. I

§ It is defined in the java servlet applicationprogramming interface (API).

§ It enables to extend the functionality of webservers.

§ It is particularly used for producingdynamic web contents.

Applications, Applets & Servlet

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java is case sensitive

• Java program must be entered in a file withfile name as the class name.

• Every statement ends with a semicolon(;).

• Every application program has a main.

Building the java program

Page 12: Ipu Java Notes

12

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

helo.javaJava program source code

Applications

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

javac

helo.java

Java compiler

Applications Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

javac

helo.java

helo.classProgram bytecode

Applications Cont.

Page 13: Ipu Java Notes

13

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

javac

helo.java

helo.class

Same procedure as for Applications

Applet

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

javac

helo.java

helo.class

NetscapeA browser

Applet Cont.

© Bharati Vidyapeeth’s 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!");

}}

•Java is case-sensitive

A Program Cont.

Page 14: Ipu Java Notes

14

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Java program consists of a named class.

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

•Java program consists of a named class.

A Program

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java program consists of a named class.• The body of the class is surrounded by braces

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• (Almost) every Java program must have one and only one main() function.

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

Page 15: Ipu Java Notes

15

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• main() must be declared as public, since itmust be called by code outside of its classwhen the program is started.

• The keyword static allows main() to becalled without having to instantiate aparticular instance of the class. This isnecessary since main() is called by javainterpreter before any objects are made.

main() in Java

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• In main(), there is only one parameter ,String args[] declares a parameter namedargs, which is an array of String storecharacter strings. In this case, args receivesany command-line arguments present whenthe program is executed.

main() in Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The body of the function is surrounded by braces

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

Page 16: Ipu Java Notes

16

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A semicolon is a statement terminator (not a statement separator).

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Statements can be combined within braces to form a compound statement.

• White space is (almost always) ignored.

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The identifier System.out is an object.• The identifier println is one of the methods for

that object.

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

Page 17: Ipu Java Notes

17

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• "Hello World" is called a string.

• There is an explicit string type in Java (unlike C++)

• Strings are different than characters

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• public indicates that this function can be called by objects outside of the class

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• void indicates that this function does not return a value to the object that calls it

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

Page 18: Ipu Java Notes

18

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• args can be used in the main function to pass parameters from the operating system command line.

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Comments are the most important part of your program• Criteria for good comments

/* Display a message */class hello {public static void main(String args[])

{System.out.println("Hello World!");

}}

A Program Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

}

}

Another Program

Page 19: Ipu Java Notes

19

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Ability to function within current Web environment

• Portability

• Device independent user interface

• Strong implementation of OOP techniques

• Security

Java’s Goals

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Important Syntax

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

JDB- java debugger(Allows you to step through the program line

at a time, set break points, and examinevariables.)

Syntax: jdb filenameJavap- Java disassembler(It displays the meaning of byte code. It also

display the accessible functions and datain a compiled class file.

Syntax: javap filename

Important Syntax Cont.

Page 20: Ipu Java Notes

20

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Javah- It creates header and stub files that letyou extend your java code with the clanguage.

Syntax: javah filename

Javadoc- It creates HTML formatdocumentation from java source code file. Touse javadoc, you have to embed thestatements /** and */. These statements arecalled documentation comment block.

Syntax: javadoc filename

Important Syntax Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Important Syntax Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• After installing the java you will get thefollowing 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.

directory tree

Page 21: Ipu Java Notes

21

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 toinstantly retype the command).

F9- It get input as Line number and go to thethat command

(e.g. Line No: 1 will go to first command)

Some Shortcut Keys.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Although complex data values arerepresented using objects, Java defines a setof 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

Data Types

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ int 32 bits signed integer

§ long 64 bits signed integer

§ float 32 bits signed floating point

number

§ double 64 bits signed floating point

number

Data Types Cont.

Page 22: Ipu Java Notes

22

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 internationalcharacters for most of the world’s livinglanguages, including Arabic, Armenian,Bengali, Bopomofo, Chinese (via unifiedHan), Cyrillic, English, Georgian,

Data Types Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Data Types Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The Unicode Standard is a character codingsystem designed to support the worldwideinterchange, processing, and display of thewritten texts of the diverse languages andtechnical disciplines of the modern world.

• Unicode provides a unique number for everycharacter, no matter what the platform, nomatter what the program, no matter what thelanguage.

Data Types Cont.

Page 23: Ipu Java Notes

23

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The Unicode Standard has been adopted bysuch industry leaders as Apple, HP, IBM,JustSystem, Microsoft, Oracle, SAP, Sun,Sybase, Unisys and many others. Unicode isrequired by modern standards such as XML,Java, ECMAScript (JavaScript), LDAP, CORBA3.0, WML, etc., and is the official way toimplement ISO/IEC 10646. It is supported inmany operating systems, all modern browsers,and many other products.

• A 16-bit character encoding used in Java.

Data Types Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The simplest terms that appear inexpressions are constants and variables.The value of a constant does not changeduring the course of a program. A variableis a placeholder for a value that can beupdated as the program runs.

• A variable in Java is most easily envisionedas a box capable of storing a value.

Constants and Variables

42

total

(contains an int)

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Each variable has the following attributes:•A name, which enables you todifferentiate one variable from another.•A type, which specifies what type ofvalue the variable can contain.•A value, which represents the currentcontents of the variable.

•The name and type of a variable are fixed.

Constants and Variables Cont.

Page 24: Ipu Java Notes

24

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The value changes whenever you assign anew value to the variable. In Java, youmust declare a variable before you can useit. The declaration establishes the nameand type of the variable and, in mostcases, specifies the initial value as well.

• The most common form of a variabledeclaration is

type name = value;

where type is the name of a Java primitive

Variable Declarations

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• type or class, name is an identifier thatindicates the name of the variable, andvalue is an expression specifying the initialvalue.

• Most declarations appear as statements inthe body of a method definition. Variablesdeclared in this way are called localvariables and are accessible only insidethat method. Variables may also bedeclared as part of a class. These arecalled instance variables.

Variable Declarations Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Operators and Operands

•Decide the semantics of expression•Meaning of operator given in languagesystem

Page 25: Ipu Java Notes

25

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Kinds of OperatorKinds of OperatorArithmetic Op. : + Arithmetic Op. : + -- * / %* / %

Relational Op. : > >= < <= == !=Relational Op. : > >= < <= == !=

Logical Op. : && || !Logical Op. : && || !

Inc/Dec Op. : ++ Inc/Dec Op. : ++ ----

Bit Op. : & | ^ ~ << >> >>>Bit Op. : & | ^ ~ << >> >>>Operators of JavaOperators of JavaConditional Conditional Op. : ?:Op. : ?:

Assign Op. : = += Assign Op. : = += --= *= /= %= &= ^= |= >>= <<= >>>== *= /= %= &= ^= |= >>= <<= >>>=Casting Op. : (Data Casting Op. : (Data

Type)Type)Array Op. : [] Array Op. : []

Method Op. : () . Method Op. : () .

instanceof Op. : instanceof instanceof Op. : instanceof

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Operator for arithmetic operation

§ Single term operator : +, -

§ Binary term operator : +, -, *, /, %

x = -5 ;x = -(-5) ;x = -(3-5) ;

Arithmetic Operator

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Operators§ + - * / %§ += -= *= /= %=§ ++ --5 / 2 à 2 (Why isn’t it 2.5 ?)

5 % 2 à 14 / 2 à 24 % 2 à 0

§ j += 6; è j = j + 6;

Arithmetic Operator Cont.

Page 26: Ipu Java Notes

26

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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)

Arithmetic Operator

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Compare two value

Result : true or false

Expression include relational operator

§ for, while, ...

Operator§ <, <=, >, >=, ==, !=

­ precedence ¯

a > b + c ===> a > (b + c)b == x < y ===> b == (x < y)

Relational Operator

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Conditional Logical Relationship of twooperands

Operator§ ! , && , ||

a < b && b < c

1 2

3

Conditional Operator

Page 27: Ipu Java Notes

27

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Expr1 ? Expr2 : Expr3 (3 Terms Operator)

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

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

Conditional Operator Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ ++, --§ Prefix operator

§ Postfix operator

§ Cannot use at expression, only at variable

§ Cannot apply at real type

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

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

(a + b)++ // error

Increment & Decrement Operator

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

&, |, <<, >>, >>>, ^, ~§ Operand should be integer type

§ Precedence

Operator PrecedenceOperator Precedence

~<< >> >>>

&^|

(H)

(L)

Bitwise Operator

Page 28: Ipu Java Notes

28

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

1’s Complement § ~ 000010102 = 111101012

Bitwise Operator

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Bitwise Shift Operator § Shift left(<<)

§ Shift right(>>)

§ Unsigned shift right(>>>)üGive this operator because Java does not support

unsigned integer.

x << y = x * 2y

x >> y = x / 2y

Bitwise Operator Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Operator§ Arithmetic operator : + - * / %§ Bitwise operator : & | ^ << >> >>>

Expr 1 = Expr 1 op Expr2 Expr1 op= Expr 2

x = x * y + 1; x *= y + 1;

x = x * (y+1)

sum = sum + i ; sum += i ;

Assignment Operators

Page 29: Ipu Java Notes

29

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Data Type Casting Operator

(int) 3.75 ===> 3(float) 3 ===> 3.0(float) (1 / 2) ===> 0.0(float)1/2 ===> 0.5

Cast Operator

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Evaluate all subexpressions in parentheses• Evaluate nested parentheses from the

inside out• In the absence of parentheses or within

parenthesesa. Evaluate *, /, or % before + or –b. Evaluate sequences of *, /, and %

operators from left to rightc. Evaluate sequences of + and – operators

from left to right

Precedence Rules

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Operator Association Precedence

() [] .! ~ ++ -- + - (Data Type) * / %+ -<< >> >>>< <= > >= instance== !=&^|&&||? := += -= *= /= %= &= ^= |= <<= >>= >>>=

Left Assoc. (High) 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. (Low)

Operator Precedence

Page 30: Ipu Java Notes

30

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

a = x + y - z ; // Left Association

b = -x ; // Right Association

c = -x++ ;

d = -++x ;

e = -x + z ;

Operator Precedence

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Example 16 + 37 % 8 / 5 is the same as6 + ((37 % 8) / 5) = 6 + ( 5 / 5) = 7

Example 26 + 37 % (8 / 5) =6 + 37 % 1 =6 + 0 = 6

Precedence Examples

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Type Conversion

Page 31: Ipu Java Notes

31

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Widening Type Conversion (Automatic Conversion)

§ Implicit conversion by compilerautomatically-when the two types arecompatible and the destination type islarger than the source type.

Type Conversion Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Type Conversion Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Narrowing Type Conversion (Casting incompatible type)§ Programmer should describe the

conversion explicitlye.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);)

Page 32: Ipu Java Notes

32

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Type Conversion Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Type Conversion Prohibit

§ boolean type

üOnly Can covert into same type

Type Conversion Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java will automatically convert intexpressions to double values without loss ofinformation

§ int i = 5;

§ double x = i + 10.5;

• To convert double expressions to int requiresa typecasting operation and truncation willoccur

§ i = (int) (10.3 * x)

Mixing Numeric Data Types

Page 33: Ipu Java Notes

33

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• To round-up instead of truncating add 0.5

§ i = (int) (10.3 * x + 0.5)

Mixing Numeric Data Types Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

Mixed Mode Operations and Strings

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

Characters as Integers

Page 34: Ipu Java Notes

34

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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”

Strings and Characters

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Single Line Comment§ int i = 10 ; // i is counter

Multiple Line Comment/*

Some comments*/

Documentation Comment/**

Documentation Comment*/

Using “javadoc” Tool,

make document

Comments

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

abstract double int super

boolean else interface switchbreak extends long synchronized

byte final native this

case finally new throwcatch float package throws

char for private transient*class goto* protected try

const* if public void

continue implements return volatiledefault import short while

do instanceof static strictfp

Java Keywords

Page 35: Ipu Java Notes

35

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ 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 Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

The if statement

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The if statement may have an optional else clause.

Syntax

if (expression)statement_1

elsestatement_2

The if statement Cont.

Page 36: Ipu Java Notes

36

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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");}

}

The if statement Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

if (x) {

if (y) a = 1;

else a = 2;

}

if (x)

if (y) a = 1;

else a = 2;

Nested if statements Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

if (x)

if (y) a = 1;

else a = 2;

Avoid confusion by using brackets.Avoid confusion by using brackets.

Nested if statements

Page 37: Ipu Java Notes

37

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Avoid confusion by using brackets.

if (x){{

if (y) a = 1;

}}

else a = 2;

Nested if statements Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Syntax

if (condition1)

statement1;

The if-else-if structure

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Syntax

if (condition1)

statement1;

else if (condition2)

statement2;

The if-else-if structure

Page 38: Ipu Java Notes

38

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Syntax

if (condition1)

statement1;

else if (condition2)

statement2;

else if (condition3)

statement3;

The if-else-if structure

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

nThe switch statement provides a multi-way decision.

char ch;switch (ch) {

}

The switch statement

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

char ch;switch (ch)

{case 'M' : case 'Q' :

}

The switch statement provides a multi-way decision

The switch statement Cont.

Page 39: Ipu Java Notes

39

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

char ch;switch (ch) {

case 'M' : ShowMenu(); break;case 'Q' : exit(0);

}

The switch statement provides a multi-way decision.

The switch statement Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The while statement continually executes ablock of statements while a particularcondition is true. Its syntax can be expressedas:

• Syntaxwhile (expression){

statements}

The while statement

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The while statementThe while statement evaluates expression,

which must return a boolean value. If theexpression evaluates to true, the whilestatement executes the statement(s) in thewhile block. The while statement continuestesting the expression and executing itsblock until the expression evaluates to false.

int i=5;while (i-- > 0)

System.out.println("X");

Page 40: Ipu Java Notes

40

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

do

statement

while (expression)

The do-while statement

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Java programming language also providesa do-while statement, which can beexpressed as follows:

do

{

statement(s)

} while (expression);

The do-while Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The difference between do-while and while isthat do-while evaluates its expression at thebottom of the loop instead of the top.Therefore, the statements within the do blockare always executed at least once.

int i=0;do {

System.out.println(‘X’); i++;

} while (i < 3);

Difference between do-while and while

Page 41: Ipu Java Notes

41

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class DoWhileDemo { public static void main(String[] args){

int count = 1; do {

System.out.println("Count is: " + count);

count++; } while (count <= 11); } }

Example of do-while

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The for statement provides a compact wayto iterate over a range of values.Programmers often refer to it as the "forloop" because of the way in which itrepeatedly loops until a particular conditionis satisfied. The general form of the forstatement can be expressed as follows:

for (initialization; termination; increment)

{ statement(s)

}

The for statement

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

The for statement Cont.

Page 42: Ipu Java Notes

42

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class ForDemo

{public static void main(String[] args)

{ for(int i=1; i<11; i++)

{ System.out.println("Count is: " + i);

}

}

}

The for statement Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

int i, sum;forfor (i=1,sum=0;i<=3;++i){

sum += i;System.out.println(sum);

}

ADVANTAGEADVANTAGEAll control information at the All control information at the

top.top.

The for statement Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• In Java, break statement is used in two waysas labeled and unlabeled.

• break is commonly used as unlabeled.

• Labeled break statement is used forterminating nested loops.

• Nested loops are loops defined inside otherloops in which the topper most loop is defineunder a label with any String value. In theexample a label String value 'weisz' isdefined above the outer most loop while.

Java Break Lable

Page 43: Ipu Java Notes

43

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Java Break Label Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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)

Java Break Label Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

break weisz;else {modulo--;continue;}}}System.out.println("\nValue at which the nested loops defined under label 'weisz' is : " + modulo);

}}

Java Break Label Cont.

Page 44: Ipu Java Notes

44

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java has two keywords break and continuein its branching category.

'break' allows users to give end to a loopwhereas with 'continue' statement flow ofcontrol inside a loop can be continued evenwhen the specified loop condition is false.'continue' statement returns the programcontrol from the point where it is passed.

Java Break continue

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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;

Java Break continue

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

do{System.out.print(" " + c[i]);

i++;

if(c[i] == c_1)break;elsecontinue;}while(c.length > i);

Java Break continue

Page 45: Ipu Java Notes

45

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 backSystem.out.println("woooooooooooooooooo");}}}

Java Break continue

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

return statement

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

When it reaches a return statementthrowing an exception, whichever occurred

first.• The return statement is used to return the

value within the body of method. The methoddeclared void does not return any value. Incase you try to get the return value from voidthe code show you a compiler error.

Java Break continue

Page 46: Ipu Java Notes

46

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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;

Java Break continue

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

if ((num1 > num2) && (num1 > num3))biggest = num1;elseif ((num2 > num3) && (num2 > num1))biggest = num2;elsebiggest = num3;return biggest;}}

Java Break continue

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The class is the fundamental concept inJAVA (and other OOPs).

• A class describes some data object(s), andthe operations (or methods) that can beapplied to those objects

• Every object and method in Java belongs toa class

• Classes have data (fields) and code (methods) and classes (member classes or inner classes)

Introduction to class

Page 47: Ipu Java Notes

47

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Static methods and fields belong to the classitself

• Others belong to instances.

Introduction to class Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Declare a class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Creating an Objectclass-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;

Page 48: Ipu Java Notes

48

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class tri{double base; double height; double area;void findarea(){area=(0.5)*(base)*(height);System.out.println(+area);}}

Example of a class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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();

}

}

Example of a class Cont.

Page 49: Ipu Java Notes

49

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The new operator allocate memory for anobject during runtime and return referenceto it. In java we cannot manipulate reference(as in C/C++ by using pointers).

• Java runtime allocate memory to an objectdynamically.

Since a class is a logical construct and anobject has physical construct. Declaring anobject of a class is two step process.

new operator

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

new operator Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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();

new operator Cont.

Page 50: Ipu Java Notes

50

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

When an object is no longer referred to by anyvariable, Java automatically reclaims memory usedby that object. This is known as garbage collection.

• Java performs garbage collection for you andeliminates the need to free objects explicitly.

• This eliminates a common cause of errors in C/C++and other languages (memory leaks). Never haveto worry about dangling references.

• When an object is no longer reachable the space itoccupies can be reclaimed.

• Space is reclaimed at the garbage collector'sdiscretion.

Garbage Collector

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• When the garbage collector is ready torelease the storage used for your object, itwill first call finalize( ), and only on the nextgarbage-collection pass will it reclaim theobject’s memory. So if you choose to usefinalize( ), it gives you the ability to performsome important cleanup at the time ofgarbage collection .

Garbage Collector Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

This is a potential programming pitfallbecause some programmers, especially C++programmers, might initially mistakefinalize( ) for the destructor in C++, which isa function that is always called when anobject is destroyed. But it is important todistinguish between C++ and Java here,because in C++ objects always get destroyed(in a bug-free program), whereas in Javaobjects do not always get garbage-collected.Or, put another way:

Garbage Collector Cont.

Page 51: Ipu Java Notes

51

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

protected void finalize() throws Throwable {} • every class inherits the finalize() method from

java.lang.Object

• the method is called by the garbage collector whenit determines no more references to the object exist

• the Object finalize method performs no actions butit may be overridden by any class

• normally it should be overridden to clean-up non-Java resources ie closing a file

• finalize() is never run more than once on anyobject

Finalization

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Two ways of argument passing in java

• Call by value

• Call by reference

1. Call by value: In java when we pass asimple type to a method, it is passed byvalue. So, the parameter that receives theargument has no effect outside themethod.

Argument passing

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Characteristics

• Original value cannot be changed

• Called method gets only a copy of thevariable.

• In java, all argument of the primitive datatypes are passed by value.

• The copy of the argument value ismaintained at a separate memory location.

Call by Value

Page 52: Ipu Java Notes

52

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class value{void change(int i){

i=i*20;System.out.println("Inside method:"+i);

}}class call{public static void main(String f[])

Call by Value Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

{value v=new value();

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

Call by Value Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Output:

C:\d>javac call.java

C:\d>java call

Before call:20

Inside method:400

After call:20

Call by Value Cont.

Page 53: Ipu Java Notes

53

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Call by reference

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Call by reference Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class test{int i;test(int j)

{i=j;}//pass by referencevoid change(test s)

Call by reference Cont.

Page 54: Ipu Java Notes

54

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

{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);

Call by reference Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

test t1=new test(20);System.out.println("Before call:"+t1.i);t1.change(t1);//calling hereSystem.out.println("After call:"+t1.i);}}Output: C:\d>javac reference.javaC:\d>java referenceBefore call:20inside method :400After call:400

Call by reference Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Static modifier

Page 55: Ipu Java Notes

55

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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;}

Static modifier Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A constructor creates an Object of the classthat it is in by initializing all the instancevariables and creating a place in memory tohold the Object. It is always used with thekeyword new and then the Class name. Forinstance, new String(); constructs a newString object.

• Sometimes in a few classes you may have toinitialize a few of the variables to values apartfrom their predefined data type specificvalues.

Constructor

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• If java initializes variables it would defaultthem to their variable type specific values.For example you may want to initialize aninteger variable to 10 or 20 based on acertain condition, when your class is created.In such a case you cannot hard code thevalue during variable declaration. such kindof code can be placed inside the constructorso that the initialization would happen whenthe class is instantiated.

Constructor Cont.

Page 56: Ipu Java Notes

56

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

public class Circle {

public static final double PI = 3.14159; // A constantpublic double r; // instance field holds circle’s

radius

// The constructor method: initialize the radius fieldpublic Circle(double r) { this.r = r; }

this.r refers to the r field of the class

Constructor Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// Constructor to use if no argumentspublic Circle() { r = 1.0; } // better: public Circle() { this(1.0); }

// The instance methods: compute values based on radiuspublic double circumference() { return 2 * PI * r; }public double area() { return PI * r*r; }

}

This() refers to a constructor for the class

Constructor Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class copy{int a,b;public copy(int a1,int b1){a=a1;b=b1;

}

Copy constructor

Page 57: Ipu Java Notes

57

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

public copy(copy c) //copy constructor{a=c.a;b=c.b;

}void view(){System.out.println("a="+a +" "+"b="+b);

}}

Copy constructor Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 constructorSystem.out.println("Second constructor");c1.view();}

Copy constructor Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

C:\d>javac copytest.javaC:\d>java copytest

First constructora=10 b=15Second constructora=10 b=15

C:\d>

Copy constructor Cont.

Page 58: Ipu Java Notes

58

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 reusability2. Save Effort

Inheritance

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Inheritance is declared using the "extends"keyword

• If inheritance is not defined, the class extends a class called Object.

Inheritance in Java

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Syntax for Class declaration that inherits a superclass

class subclass-name extends superclass-name

{// body of class}

• Subclass have more functionality than superclass

Inheritance in Java Cont.

Page 59: Ipu Java Notes

59

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Inheritance in Java Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Single Inheritance-One base class and one Derived class

Person

Employee

Types of Inheritance

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Types of Inheritance Cont.

Page 60: Ipu Java Notes

60

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Employee

Part-TimeEmployee

Person

Doctor

Neuro-Surgon

Types of Inheritance Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Vehicle Asset

Employee Vehicle

Griffin

LionEagle

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.

Note: We can implement it by using Interfaces.

Types of Inheritance Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Hierarchical- More than one child class hassame parent class.

Person

Employee Customer

Types of Inheritance Cont.

Page 61: Ipu Java Notes

61

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Full-Time

CustomerEmployee

Person

CasualRegularPart-Time

Hybrid- Mixture of more than one inheritance.

e.g.

Types of Inheritance Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class A{

int I,j;void showij(){

System.out.println(“I and j::” +i+ ” ”+j);}

}{ Sytem.out.println(“i+j+k:”+(i+j+k));

}}

Inheritance Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class B extends A{Int k;void showk(){System.out.println(“k:”+k);

}void sum()

Inheritance Example

Page 62: Ipu Java Notes

62

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class inheritance{public static void main(String s[])

{A a1=new A();B b1=new B();//The superclass may be used by itselfa1.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 */

Inheritance Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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();}}

Inheritance Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Contents of superclass I and j: 10 20

Contents of Subclass I and j:7 8K:9

Sum of I , j and k in Sub classi+j+k:24

Inheritance Example

Page 63: Ipu Java Notes

63

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• An array is a collection of elements whereeach 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 iscreated. It cannot change.

Array(s) in Java

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Array(s) in Java

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Creating an array is a 2 step processIt must be declared (declaration does not specify size)

type[] arrayName;declaration syntax:

note the location of the []

Creating Array

Page 64: Ipu Java Notes

64

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Creating Array Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

When an array is created, all of itselements are automatically initialized

1. 0 for integral types2. 0.0 for floating point types3. false for boolean types4. null for object types

Creating Array Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

int[] grades = new int[5];

maximum array index is length -1

array indices

0

4

3

2

1

grades

0

0

0

0

0

Creating Array Cont.

e.g.

Page 65: Ipu Java Notes

65

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Because array elements are initialized to 0,thearray should be initialized with usable valuesbefore 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 indexand []

Initializing and Using Arrays

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

int[] sequence = new int[5];

for (int i=0; i< sequence.length; i++){

sequence[i] = i * 25;}

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

array length: ensures loopwon't go past end of the array

Initializing and Using Arrays

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Another way of initializing lists is by usinginitializer lists.– The array is automatically created– The array size is computed from the numberof items in the list.

Using initializer lists

int[] grades = {100, 96, 78, 86, 93};

type[] arrayName = {initializer_list};

Page 66: Ipu Java Notes

66

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Whenever and array is accessed, the index ischecked to ensure that it within the bounds ofthe array.

• Attempts to access an array element outsidethe bounds of the array will cause anArrayIndexOutOfBounds exception to bethrown.

Array Bounds Checking

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

ArrayIndexOutOfBoundsException

int[] sequence = new int[5];

sequence[0] = 50; // oksequence[1] = 60; // oksequence[-1] = 100; // Exceptionsequence[5] = 30; // Exception

Array Bounds Checking

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

You may recall that the main method takes an arrayof String objects as a parameter. This array ofStrings holds the command line parameters whichwere passed to the java program when it wasstarted

The main() method

public class HelloWorld{

public static void main(String[] args){

System.out.println("Hello World");}

}Array holding command line parameters

Page 67: Ipu Java Notes

67

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Command line parameters

4

3

2

1

0

args

java HelloWorld This is a test, Jim

This

is

Jim

a

test,

name of class containing the main() method

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Arrays with multiple dimensions can also be created.

• They are created and initialized in the same way as single dimensioned arrays.

Multi-dimensional Array

type[][] arrayName;declaration syntax:

each [] indicates another dimension

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

e.g.

String[][] colours = {{"Red", "Green", "Blue"},{"Cyan", "Magenta", "Yellow"},{"Russet", "Mauve", "Orange"}};

int[][] grades = new int[20][5];for(int i = 0; i< 20; i++)

for(int j = 0; j<5; j++)grades[i][j] = 100;

Multi-dimensional Array Cont.

Page 68: Ipu Java Notes

68

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• An array is the collection of same data type.Suppose if we have a declare an array oftype String, then it will store only the Stringvalue not any other data type. When we havea closely related data of the same type andscope, it is better to declare it in an array.

String Array

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

e.g. String array

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

Using initializer lists

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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]);}

}}

String Array Example

Page 69: Ipu Java Notes

69

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

•An object of the String class represents a string ofcharacters.

•The String class belongs to the java.lang package,which does not require an import statement.

•Like other classes, String has constructors andmethods. Unlike other classes, String has twooperators, + and += (used for concatenation).

•String objects are handled specially by the compiler.•String is the only class which has "implicit"instantiation.

The String Class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The String class is defined in the java.langpackage.

• Strings are immutable.

The value of a String object can never bechanged.

§ For mutable Strings, use the StringBufferclass.

The String Class Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

String str = "abc"; is equivalent to:char data[] = {'a', 'b', 'c'};String str = new String(data);

Here are some more examples of how stringscan 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);

The String Class Cont.

Page 70: Ipu Java Notes

70

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The class String includes methods forexamining individual characters of thesequence, for comparing strings, forsearching strings, for extracting substrings,and for creating a copy of a string with allcharacters translated to uppercase or tolowercase. Case mapping is based on theUnicode Standard version specified by theCharacter class.

The String Class Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Java language provides special support forthe string concatenation operator ( + ), andfor conversion of other objects to strings.String concatenation is implemented throughthe StringBuilder(or StringBuffer) class andits append method. String conversions areimplemented through the method toString,defined by Object and inherited by all classesin Java. For additional information on stringconcatenation and conversion, see Gosling,

The String Class Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Joy, and Steele, The Java LanguageSpecification.

• Unless otherwise noted, passing a nullargument to a constructor or method in thisclass will cause a NullPointerException to bethrown.

The String Class Cont.

Page 71: Ipu Java Notes

71

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A String represents a string in the UTF-16format in which supplementary charactersare represented by surrogate pairs in theCharacter class for more information). Indexvalues refer to char code units, so asupplementary character uses two positionsin a String.

• The String class provides methods fordealing with Unicode code points (i.e.,characters), in addition to those for dealingwith Unicode code units (i.e., char values).

The String Class Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Normally, objects in Java are created with the new keyword.

However, String objects can be created "implicitly":

Creating String Objects

String name;name = new String("Craig");

String name;name = "Craig";

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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";

Creating String Objects Cont.

Page 72: Ipu Java Notes

72

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The String class has many methods. The mostcommonly used are:

– length() - returns the number of characters inthe String

– charAt() - returns the character at thespecified index

– equals() - returns true if two strings haveequal contents

– compareTo() -returns 0 if equal,-# if one String is "less than” the other,+# if one String is "greater than" the other.

Commonly used String methods

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ indexOf() - returns the index of specifiedString or character

§ substring() -returns a portion of theString's text

§ toUpperCase(), toLowerCase() - convertsthe String to upper or lower casecharacters

Commonly used String methods

© Bharati Vidyapeeth’s 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");

Page 73: Ipu Java Notes

73

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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;

String Examples Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Important note: The == operator cannot beused to test String objects for equality

Variables of type String are references toobjects (ie. memory addresses)Comparing two String objects using ==actually compares their memoryaddresses. Two separate String objectsmay contain the equivalent text, but resideat different memory locations.

• Use the equals method to test for equality.

Testing Strings for Equality

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• StringBuffer objects are similar to Stringobjects

§ Strings are immutable

§ StringBuffers are mutable

• The StringBuffer class defines methods formodifying the String value

§ insert()

§ append()

§ setLength()

The StringBuffer Class Cont.

Page 74: Ipu Java Notes

74

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

To clear a StringBuffer, set it's length to 0

The StringBuffer Class

StringBuffer nameBuffer = new StringBuffer("Joe");

[...]nameBuffer.setLength(0); // clear StringBuffer

© Bharati Vidyapeeth’s 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 Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

String Tokenizer:- This class provides amethod to break a string into token parsing.A string involves breaking the string intodifferent words. These words are calledtoken. The StringTokenizer uses whitespaces as separators. This is known asdelimiters.

countToken() // count the no. of tokens in thestring

String Tokenizer

Page 75: Ipu Java Notes

75

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

hasMoreToken() // Test whether more tokens are avail in the string

nextToken // Returns the next token in the string

Note: import java.util.*; package.

String Tokenizer Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

StringTokenizer Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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]); } }}

StringTokenizer Example Cont.

Page 76: Ipu Java Notes

76

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Wrapper Classes: Primitive data types may beconverted into object type by using thewrapper classes. These wrapper classes areavailable in the java.lang package. So wecan use it without an import statement.

There are eight wrapper classes:• Byte• Boolean• Character• Short

Wrapper Classes

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Wrapper Classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• These wrapper classes encapsulate(or)‘wraps up’ a primitive type. So that a variablecan be represented by an object whennecessary.

• Theses classes also have a constantsMAX_VALUE and MIN_VALUE.

Wrapper Classes Cont.

Page 77: Ipu Java Notes

77

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Integer Class: The Integer class is a wrapperclass for primitive data type int.

• It wraps a value of the primitive type int in anobject.

• This class provides methods for convertingan int to String object and String to an int.

• parseInt(String s) //convert string to integer nreturn value int

• toBinaryString(int n) // returns a String thatcontain binary equivalent of n

Integer Class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• toHexString(int n) // returns a String thatcontain hexadecimal equivalent of n

• toOctalString(int n) // returns a String thatcontain Octal equivalent of n.etc.

Integer Class Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Double class

Page 78: Ipu Java Notes

78

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The java.lang is one of the most importantpackages in java. It provides the fundamentalfor java programming, its most importantclasses are:

• Object

• Class

• Math

• String

• StringBuffer

• System andThread, etc

java.lang package

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The System class: It is one of the mostimportant classes in the java.lang package.It provide a standard interface to standardinput,ouput and error.

• System.in.read(); //input

• System.out.println(“helo”); //output

• System.err.println(“Error”); //error

The System class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Class Class: This is used to find runtimestate of an object or interface. Objects of typeclass are created automatically when classesare loaded.

• getName()=returns the complete name of theclass or interface of the invoking object.

• getSuperClass()=returns the super class ofthe invoking object.

The Class Class

Page 79: Ipu Java Notes

79

Page 80: Ipu Java Notes

80

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

super Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• When a subclass calls super(), it is callingthe constructor of its immediate superclass.

• Thus super(), always refers to the superclassimmediately above the calling class. This istrue even in multileveled hierarchy.

super Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Second use for superSimilar to this, excepts it always refer to thesuperclass of the subclass in which it isused.Syntax super.member•Method can be method or variable•This form is applicable to situations in whichmember names of a subclass hidesmembers by the name in the superclass.

Super Cont.

Page 81: Ipu Java Notes

81

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

//using super to overcome name hidingclass A{

int i;}//create a subclass by extending class Aclass B extends A{

int i; //this I hides the i in A

Super Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

B(int a,int b){super.i=a; //i in Ai=b; //i in B}void show(){System.out.println(“i in superclass:” +super.i); //Result

1System.out.println( “i in subclass:” + i); //Result 2}}

Super Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Super Example

Page 82: Ipu Java Notes

82

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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, themethod must be overridden.

• To override a method, provide animplementation in the subclass.

Method Overriding

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The method in the subclass MUST have theexact name and same signature (name &type) as the method it is overriding. elseoverloaded

Method Overriding

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Method Overriding Example

Page 83: Ipu Java Notes

83

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

void show(){

System.out.println("Inside Subclass");}}

class override{public static void main(String s[]){b b1=new b();b1.show();

}}

Method Overriding Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

First of all, we should understand what is themeaning of 'abstract' in terms of software.

• It's the same meaning as in English, that is,the entities (objects) which do not exist in thereal world are abstract entities.

• For example, Dog, Cat, Bear, Deer are allanimals that exist but animal is also an entitywhich is just a concept and there is noexistence's we can define an abstract classfor 'Animal'.

Introduction Abstract

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• We can derive any number of real worldanimal classes from the abstract class'Animal' like Tiger, Lion, etc.

• Obviously, we can understand now why wecannot create objects for abstract classes.

• Because the Animal class has no existencein real world. So we cannot create a realworld entity (nothing but an object).

Introduction Abstract

Page 84: Ipu Java Notes

84

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• That is the very reason this concept isfollowed. The derived classes that we'veseen above are concrete classes since theyare real world objects and have definiteproperties and operations on them.

Abstract: It allows the implementation of abehavior in different ways. The class andmethods declared using abstract modifier arenot complete. The implementation is done insubclass. It is opposite to final modifier.

Introduction Abstract

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• It can have abstract method.• If we are giving abstract specifier, then the

class cannot be instantiated, because it isincomplete.

• If it is declared as in method, it has no bodyand belong to an abstract class. So subclassmust override the abstract methods of thesuperclass.

• We cannot use the final and abstract modifierfor the same class, method or data member.

• An abstract class can have concrete methodsalso.

Abstract Class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A class for which object is not created, i.e. Anabstract class cannot be directly instantiatedwith the new operator, Such objects would beuseless, because an abstract class is notfully defined. Also we cannot declare abstractconstructors, or abstract static methods. Anysubclass of an abstract class must eitherimplement all of the abstract methods in thesuperclass , or be itself declared abstract.

Abstract Class

Page 85: Ipu Java Notes

85

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Abstract function-A function for whichbody({….}) is not defined.

Syntax: abstract type name(parameter-list)

Abstract function

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

abstract class A

{

abstract void callme();

void callmetoo()

{

System.out.println(“This is a concrete method”);

}

}

Abstract Class Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class B extends A{

void callme()

{

System.out.println(”B’s implementation of callme”);

}

}

Abstract Class Example

Page 86: Ipu Java Notes

86

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class demo

{

public static void main(String s[])

{

B b=new B();

b.callme();

b.callmetoo();

}

}

Abstract Class Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Output:

B’s implementation of call me

This is a concrete method

Abstract Class Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Concrete class:

• It specifies the full set of methods for an object.

• It implements all of its methods.

• Can have instance.

• Can have subclass

• Can have constructor.

Difference between concrete and abstract class

Page 87: Ipu Java Notes

87

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Difference between concrete and abstract class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A final class cannot be subclassed. This isdone for reasons of security and efficiency.Accordingly, many of the Java standardlibrary classes are final, for examplejava.lang.System and java.lang.String. Allmethods in a final class are implicitly final.

Example:

public final class MyFinalClass {...}

final Class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A final method cannot be overridden bysubclasses. This is used to preventunexpected behavior from a subclass alteringa method that may be crucial to the functionor consistency of the class.

Example:

public class MyClass { public final voidmyFinalMethod() {...}}

final methods

Page 88: Ipu Java Notes

88

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A final variable can only be assigned once.This assignment does not grant the variableimmutable status. If the variable is a field of aclass, it must be assigned in the constructorof its class. (Note: If the variable is areference, this means that the variablecannot be re-bound to reference anotherobject. But the object that it references is stillmutable, if it was originally mutable.)

• Unlike the value of a constant, the value of afinal variable is not necessarily known atcompile time.

final variable

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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)

final variable Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

final variable Example Cont.

Page 89: Ipu Java Notes

89

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Object class: All the classes are subclassof the object class and inherit its methods.Object, which is the root of the java classhierarchy. The toString() method creates astring representation of the value of an objectof the object class.

• wait() and notify() are methods of the objectclass and used for controlling threads, etc.

• clone(), equals() & hashcode(), getClass(), finalize()these methods also belongs to the object class.

Object class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Interfaces are syntactically similar to classes,but they lack instance variables, and theirmethods are declared without any body.

• Once it is defined, any no. of classes canimplement an interface. Also, one class canimplement any no. of interfaces.

• To implement an interface, class must createthe complete set of methods defined by theinterface. However each class is free todetermine the details of its ownimplementation.

Interface

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• By providing “interface” keyword java allowsyou to fully utilize the “one interface, multiplemethods” aspect of polymorphism.

Note: Since Java has single inheritance ofimplementation - you can extend only oneclass.

Introduction Interface Cont.

Page 90: Ipu Java Notes

90

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• But Java has multiple interface inheritance.

• All methods in an interface are implicitlyabstract.

• Each class that implements the interfacemust implement all its methods.

• Methods in an interface are always public.

• Fields in an interface are always static andfinal.

Introduction Interface Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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;}

Interface Syntax

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Where, access is either public or not used.When no access specifier is included, thendefault access results, and the interface isonly available to other members of thepackage in which it is declared.

• name is the name of interface, and can beany valid identifiers.

• The method which are declared have nobodies. They end with a semicolon after theparameter list.(// like abstract methods)

Interface Syntax

Page 91: Ipu Java Notes

91

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Variables can be declared inside of interfacedeclarations. They are implicitly final andstatic, they cannot be changed by theimplementing class. They must alsoinitialized with a constant value.

• The methods that implement an interface must be declared public.

e.g interface call{void callme(parameter);

}

Interface Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Implementing Interface

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

e.g.

public class Test1 extends Test2 implements

NewInterface

{

// class body

}

Java Interface to achieve multiple inheritance

Page 92: Ipu Java Notes

92

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Interfaces are essential to the Java language.Interfaces have advantages over classes becauseof improved information hiding and code re-use.They provide multiple inheritance. Interfaces alsosolve the nasty virtual class problem in C++. Virtualclasses are a counterintuitive solution to theproblem of a class inheriting from the same classmore than once. This is equivalent in Java to thesituation where a base class and derived classimplement the same interface. Interfaces thatextend other interfaces may also produce duplicatereferences. Java merges the duplicate referencesinto one without any fuss

Conclusion

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Static (keyword):- Normally a class membermust be accessed only in conjunction with anobject of its class. However, it is possible tocreate a member that can be used by itself,without reference to a specific instance. Tocreate such a member, precede itsdeclaration with the keyword static.

• When a member is declared static, it can beaccessed before any objects of its class arecreated, and without reference to any object

static

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• We can declare both methods and variablesto be static.

e.g. the most common example of a staticmember is main(). main() is declared asstatic because it must be called before anyobject exist.

• Variables-Instance variable declared as staticare, essentially, global variables. Whenobjects of its class are declared, no copy of astatic variable is made. Instead, all instancesof the class share the same static variable.

static Cont.

Page 93: Ipu Java Notes

93

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Static Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Abstract classes: are used only when there is a “is-a” 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.

Difference between Abstract class and Interface

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• interface contains methods that must be abstract; abstract class may contain concrete methods

• interface contains variables that must be static and final; abstract class may contain non-final and final variables.

• members in an interface are public by default, abstract class may contain non-public members

Difference between Abstract class and Interface

Page 94: Ipu Java Notes

94

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• interface is used to "implements"; whereas abstractclass is used to "extends".

• interface can be used to achieve multipleinheritance; abstract class can be used as a singleinheritance.

• interface can "extends" another interface,abstract class can "extends" another classand "implements" multiple interfaces.

• interface is absolutely abstract; abstract classcan be invoked if a main() exists.

Difference between Abstract class and Interface

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces. If given a choice, use interface instead of abstract class.

Similarities:Neither Abstract classes or Interface can be instantiated.

Difference between Abstract class and Interface

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Interface is also extended by other interface.One interface can inherit another by use ofthe keyword extends. This is much like a wayfor inheriting class. When you inheriting twointerfaces, you must provide implementationsfor all methods defined within the interfaceinheritance path.

Extending Interface

Page 95: Ipu Java Notes

95

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

interface one{void print1();void print2();

}interface two extends one{void print3();

}

Extending Interface Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The main feature of OOP is its ability tosupport the reuse of code:§ Extending the classes (via inheritance)§ Extending interfaces

• The features in basic form limited to reusingthe classes within a program.

• What if we need to use classes from otherprograms without physically copying theminto the program under development ?

Putting classes together by using package

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• In Java, this is achieved by using what isknown as “packages”, a concept similar to“class libraries” in other languages.

• Packages are Java’s way of grouping anumber of related classes and/or interfacestogether into a single unit. That means,packages act as “containers” for classes.

Introduction Package(s)

Page 96: Ipu Java Notes

96

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The benefits of organising classes intopackages are:§ The classes contained in the packages of

other programs/applications can bereused.§ In packages classes can be unique

compared with classes in other packages.That two classes in two different packagescan have the same name. If there is anaming clash, then classes can beaccessed with their fully qualified name.

Benefits of Package(s)

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ Classes in packages can be hidden if wedon’t want other packages to access them.

§ Packages also provide a way forseparating “design” from coding.

Benefits of Package(s) Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Since packages are collection of relatedclasses.

These are of two types:

1. Predefined package (Java API Package, orBuilt-in package)

2. User-Defined package

Types of Package(s) Cont.

Page 97: Ipu Java Notes

97

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

Predefined package

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Predefined package Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ java.net

üClasses for networking

§ java.applet

üClasses for creating and implementing applets

Predefined package Cont.

Page 98: Ipu Java Notes

98

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.*;

Accessing Classes from Packages

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Selected or all classes in packages can be imported:

• Implicit in all programs: import java.lang.*;• package statement(s) must appear first .

Accessing Classes from Packages Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java supports a keyword called “package”for creating user-defined packages. Thepackage statement must be the firststatement in a Java source file (exceptcomments and white spaces) followed byone or more classes.

Creating Packages

Page 99: Ipu Java Notes

99

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Package name is “myPackage” and classesare considered as part of this package; Thecode is saved in a file called “ClassA.java”and located in a directory called“myPackage”.

package myPackage;public class ClassA {

// class body}class ClassB {// class body}

Creating Packages Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Classes in one ore more source files can bepart of the same packages.

• As packages in Java are organisedhierarchically, sub-packages can be createdas follows:§ package myPackage.Math§ package

myPackage.secondPakage.thirdPackage

Creating Sub Packages

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Store “thirdPackage” in a subdirectory named“myPackage\secondPackage”.

• Store “secondPackage” and “Math” class in asubdirectory “myPackage”.

Creating Sub Packages Cont.

Page 100: Ipu Java Notes

100

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

Accessing a Package

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ All classes/packages from higher-level package can be imported as follows:

üimport myPackage.*;

Accessing a Package Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• All classes (or interfaces) accessible to allothers in the same package.

• Class declared public in one package isaccessible within another. Non-public class isnot

• Members of a class are accessible from adifference class, as long as they are notprivate

• protected members of a class in a packageare accessible to subclasses in a different class

Protection and Packages

Page 101: Ipu Java Notes

101

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Public keyword applied to a class, makes itavailable/visible everywhere. Applied to amethod or variable, completely visible.

• Private fields or methods for a class onlyvisible within that class. Private members arenot visible within subclasses, and are notinherited.

• Protected members of a class are visiblewithin the class, subclasses and also withinall classes that are in the same package as thatclass.

Visibility - Revisited

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Accessible to: public protected Package(default)

private

Same Class Yes Yes Yes Yes

Class in package Yes Yes Yes No

Subclass indifferent package

Yes Yes No No

Non-subclassdifferent package

Yes No No No

Visibility Modifiers

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Consider an existing package that contains aclass called “Teacher”:

• This class is stored in “Teacher.java” filewithin a directory called “pack1”.

• How do we a new public class called“Student” to this package.

package pack1;public class Teacher{// class body

}

Adding a Class to a Package

Page 102: Ipu Java Notes

102

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Define the public class “Student” and place thepackage statement before the class definitionas follows:

package pack1;public class Student{// class body

}class Teacher

package pack1;

class Student

Adding a Class to a Package Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Store this in “Student.java” file under the directory“pack1”.

• When the “Student.java” file is compiled, the classfile will be created and stored in the directory“pack1”. Now, the package “pack1” will contain boththe classes “Teacher” and “Student”.

Adding a Class to a Package Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• When packages are developed by differentorganizations, it is possible that multiplepackages will have classes with the samename, leading to name classing.

class Teacher

package pack1;

class Student

class Student

package pack2;

class Courses

Packages and Name Clashing

Page 103: Ipu Java Notes

103

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

We can import and use these packages like:

§ import pack1.*;

§ import pack2.*;

§ Student student1; // Generates compilation error

Packages and Name Clashing

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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;

Handling Name Clashing

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A new class called “Professor” can becreated by extending the “Teacher” classdefined 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.}

Extending a Class from Package

Page 104: Ipu Java Notes

104

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Packages allow grouping of related classesinto a single united.

• Packages are organised in hierarchicalstructure.

• Packages handle name classing issues.

• Packages can be accessed or inheritedwithout actual copy of code to each program.

Conclusion

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Java offers the real possibility that most programscan be written in a type-safe language. However,for Java to be broadly useful, it needs to have moreexpressive power than it does at present.

It allows students to learn object-orientedprogramming without exposing them to thecomplexity of C++. It provides the kind of rigorouscompile-time error checking typically associatedwith Pascal. It allows instructors to introducestudents to GUI programming, networking, threads,and other important concepts used in modern-daysoftware.

Conclusion

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Java is a popular, mature language that ishighly portable, features a large standardlibrary and automatic memory handling. Onthe downside, it’s an interpreted languagewith no support for unsigned types and theautomatic memory management preventsfine control over memory use and makesporting of algorithms harder. Whether Javais a good choice for your scientificprogramming will depend upon which ofthese pros or cons is of most benefit or cost.

Summary

Page 105: Ipu Java Notes

105

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

Page 106: Ipu Java Notes

106

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

Page 107: Ipu Java Notes

107

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

Page 108: Ipu Java Notes

108

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Short answer type QuestionsQ1)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?

Review Questions cont..

Page 109: Ipu Java Notes

109

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Q8)How can a subclass call a method or a constructor definedin a superclass?

Q9)What is the difference between static and non-staticvariables? What is a static method?

Q10) Which class should you use to obtain design informationabout an object?

Review Questions cont..

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Long answer type QuestionsQ1)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?

Review Questions cont..

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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?

Review Questions cont..

Page 110: Ipu Java Notes

110

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 0-321-24678-0 (see also online edition of the specification).

Suggested Reading/References

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63 ‹#›

UNIT-2

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Exception Handling

• Multithreaded Programming

• Input/Output Programming

• Networking

Learning Objectives

Page 111: Ipu Java Notes

111

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

What is the difference between error and anexception?

• An error is an irrecoverable conditionoccurring at runtime. Such as OutOfMemoryerror, StackOverFlow.

• These JVM errors and you can not repairthem at runtime. While exceptions areconditions that occur because of bad inputetc. e.g. FileNotFoundException will bethrown if the specified file does not exist.

Exception & Error

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Or a NullPointerException will take place ifyou try using a null reference.

• In most of the cases it is possible to recoverfrom an exception (probably by giving user afeedback for entering proper values etc.)

Exception & Error

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

What are runtime exceptions

• Runtime exceptions are those exceptionsthat are thrown at runtime because of eitherwrong input data or because of wrongbusiness logic etc. These are not checked bythe compiler at compile time

Runtime exceptionsRuntime Exception

Page 112: Ipu Java Notes

112

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• An exception is an abnormal condition thatarises 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 apiece of code.When an exceptional condition arises, andobject representing that exception is createdand thrown in the method that cause theerror, that method may choose to handle theexception itself or pass it on.

Exception

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java exception handling is managed via five keywords:

try, catch, throw, throws and finally.

Exception Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

try

• Programs statements that we want to monitorfor 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 isthrown.

try

Page 113: Ipu Java Notes

113

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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}

catch

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

catch(ExceptionType2 exob)

{

//exception handler for ExceptionType2

}

Catch Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Exception type is the type of exception thathas occurred.

• Uncaught Exception Any exception that is notcaught by the program, will ultimately beprocessed by the default handler.

• Default handler displays a string describingthe exception, prints a stack trace from thepoint at which the exception occurred, andterminates the program, default handlerprovided by the Java run-time system.

Exception Type

Page 114: Ipu Java Notes

114

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class ecep

{

int d=0;

int a=42/d;

}

Output:

Java.lang.ArithmeticEception: / by zero

at ecep.main(ecep.java:4)

Exception Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The stack trace will always show thesequence of method invocations that ledup to the errors.

Exception Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class excp{static void sub(){int d=0;int a=10/d;

}public static void main( String s[]){excp.sub()}}

Exception Example Cont.

Page 115: Ipu Java Notes

115

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Output:

Java.lang.ArithmeticException: / by zero

at excp.subroutine(excep.java:4)

at excep.main(excep.java:7)

• The bottom of the stack is main’s line 7,which is the call to sub(), which caused theexception at line 4.

Exception Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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");}}}

try Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

try- to handle a run time error, simply enclosethe code that you want to monitor inside a tryblock. Immediately following the try block,include a catch clause that specifies theexception type that you wish to catch.

Multiple catch clause- In some cases, morethan one exception could be raised by asingle piece of code. To handle this type ofsituation, use two or more catch clause, eachcatching a different type of exception. When

Multiple Catch

Page 116: Ipu Java Notes

116

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

an exception is thrown, each catchstatement is inspected in order, and thefirst one whose type matches that of theexception is executed. After one catchstatement executes, the others arebypassed, and execution continues aftertry/catch block.

Multiple Catch Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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; }

Multiple catch Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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");}}

Multiple catch Example Cont.

Page 117: Ipu Java Notes

117

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

C:\java\bin>javac multi.java

C:\java\bin>java multia=0divide by zerojava.lang.ArithmeticException: / by zeroAfter try/catch blocksC:\java\bin>javac multi.javaC:\java\bin>java multia=0divide by zeroAfter try/catch blocks

Multiple catch Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The try statement can be nested. That is , atry statement can be inside the block ofanother try. Each time a try statement isentered, the context of that exception ispushed on the stack. If a inner try statementdoes not have a catch statement’s catchhandlers are inspected for a match.

Nested try

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

This continues until one of the catchstatements succeeds, or until all of thenested try statements are exhausted. If nocatch statement matches, then the java run-time system will handle the exception.

Nested try Example

Page 118: Ipu Java Notes

118

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 zeroif (a==2) {

int c[]={1};c[42]=99;

}}

Nested try Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}}

}

Nested try Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

C:>java nesttryDivide by0; java.lang.ArithmeticException: / by

zeroC:\> java nesttry ona=1Divide by0; java.lang.ArithmeticException: / by

zeroC:\>java nesttry one twoa=2Array index out-of-bounds:

java.lang.ArrayIndexOutOfBoundsException

Nested try Example Cont.

Page 119: Ipu Java Notes

119

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• So far, you have only been catchingexceptions that are thrown by Java run-timesystem. However, it is possible for yourprogram to throw an exception explicitly, usingthe throw statement. The general form ofthrow is shown here:

• throw ThrowableInstance;

• Here, ThrowableInstance must be an object oftype Throwable or a subclass of Throwable.

throw

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• There are two ways you can obtain a Throwableobject: using a parameter into a catch clause, orcreating one with the new operator.

• The flow of execution stops immediately after thethrow statement; any subsequent statements arenot executed. The nearest enclosing try block isinspected to see if it has a catch statement thatmatches the type of the exception. If it does find amatch, control is transferred to that statement. Ifnot, then the next enclosing try statement isinspected, and so on. If no matching catch is found,then the default exception handler halts theprogram and prints the stack trace.

throw Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class ThrowDemo{static void demopro(){try{

throw new NullPointerException(“demo”);}catch(NullPointerException e){System.out.println(“Caught inside

dempproc.”);throw e; //rethrow the exception}}

throw Example

Page 120: Ipu Java Notes

120

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

throw Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

throw new NullPointerException(“demo”);

Here, new is used to construct an instanceof NullPointerException. All of java’s built-in run time exceptions have at least twoconstructors:

• one with no parameter, and

• one that takes a string parameter.In the second form the argument specifies astring that describes the exception.

throw Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• If a method is capable of causing anexception that it does not handle, it mustspecify this behavior so that callers of themethod can guard themselves against thatexception. We do this by including a throwsclause in the method’s declaration. A throwsclause exceptions, except those of the typeError or RuntimeException, or any of theirsubclasses. All other exceptions that amethod can throw must be declared in thethrows clause. If they are not, a compile-timeerror will result.

throws Example

Page 121: Ipu Java Notes

121

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

throws Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class ThrowsDemo{static void throwOne() throws

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

throws Example Cont.

© Bharati Vidyapeeth’s 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

Page 122: Ipu Java Notes

122

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• finally creates a block of code that will beexecuted after a try/catch block hascompleted and before the code followingthe try/catch block. The finally block willexecute whether or not an exception isthrown. If an exception is thrown, the finallyblock will execute even if no catchstatement matches the exception. Any timea method is about to return to the callerfrom inside a try/catch block, via anuncaught exception or an explicit returnstatement, the finally clause is alsoexecuted just before the method returns.

finally

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• This can be useful for closing file handlesand freeing up any other resources thatmight have been allocated at the beginningof a method with the intent of disposing ofthem before returning. The finally clause isoptional. However, each try statementrequires at least one catch or a finally clause.

finally Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class finallyDemo{static void procA(){try{System.out.println(“inside procA”);throw new RuntimeException(“demo”);}Finally{System.out.println(“ProcA’s finally”);}}

finally Example Cont.

Page 123: Ipu Java Notes

123

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

static void procB(){try{System.out.println(“inside procB”);return;}finally{System.out.println(“procB’s finally”);}}

static void procC(){try{System.out.println(“inside procC”);}finally{System.out.println(“procC’s finally”);} }

finally Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

finally Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Out put:Inside procAprocA’s finallyExceptioncaughtInside procBprocB’s finallyInside procCprocC’s finally

finally Example Cont.

Page 124: Ipu Java Notes

124

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

UncheckedArithmeticException Arithmetic error, such as divided-by-zeroArrayIndexOutOfBoundsException 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.

Java’s Built-in Exception

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

throw- is used to throw an exceptionexplicitly.

Creating your own Exception Subclasses

• You can create your own Exception typesto handle situations specific to yourprogram.

• String toString(), Returns a string objectcontaining a description of the exception.

Java’s custom Exception

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class user-e{public static void main(String s[]){int marks=15;try{

if(marks<30)throw new myException();else

System.out.println(“PASS”);

Custom Exception Example

Page 125: Ipu Java Notes

125

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}}}

Custom Exception Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class myException extends Exception

{

myException()

{

super(“FAIL”);

}

}

Output:myException:FAIL

Custom Exception Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Checked Exception- Java compiler checks that youhave indeed stated what is to be done when theyarise, and it is because of this checking that theyare called checked exception. The checkedexceptions describe problems that can arise in acorrect program, typically difficulties with theenvironment such as user mistake or I/O programs.In any method that contains some statements thatmight throw checked exception you must eitherthrows the exception using a throws constraint inthe declaration of the method.

Checked Exception

Page 126: Ipu Java Notes

126

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Checked ExceptionClassNotFoundException Class not foundIlligalAccessException Access to a class is deniedInstantiationException Attempt to create an object of an

abstract class or interfaceInterruptedException One thread has been interrupted

by another threadNoSuchFieldException A requested field does not existNoSuchMethodException A requested method does not exist

Checked Exception

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Thread- A thread is similar to a sequentialprogram. A sequential program has abeginning, a sequence of steps to beexecute, and an end. A thread also has abeginning, a sequence and an end.However, a thread is not a program on itsown but runs within a program.

• A thread can be defined as the sequentialflow of control within a program.

Thread

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Every program has at least one thread that iscalled the primary thread. We can createmore threads when necessary.

Thread Cont.

Page 127: Ipu Java Notes

127

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Use-Threads are very useful when we havelarge computation that take severalseconds to complete, and user should notperceive the delay. Animation is anotherarea where threads are used.

• Most computer games use graphics and thescore and the audio effects go onsimultaneously.

Application of Thread

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A single game has all these elements beingprocessed at the same time. The programhas been divided into three sub-units andeach subunit is handled by a thread.

• Java has built-in support for threads. A majorportion of the java architecture ismultithreaded.

• In java programs, the most common use of a threadis to allow the applet to accept input from user andat the same time , display animation in another partof the screen.

Application of Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A process that is made only one thread issaid to be “single –threaded”.

• A single threaded application can performonly one task at a time. In such a situationyou wait for one task to complete so thatanother can start.

• A process having more than one thread issaid to be multithreaded.

Single Thread

Page 128: Ipu Java Notes

128

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Multithread

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Multiple threads in a process run at thesame time, perform different tasks andinteract with each other.

• e.g. Microsoft internet explorer, is a webbrowser within browser, we can print a pagein the background , while you are scrolling apage. You can play audio and watchanimated images at the same time.

• This behavior is close to real life whereyou perform several tasks concurrently.

Multithreaded Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

}

Thread Class

Page 129: Ipu Java Notes

129

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

AND

Access_specifier <class_name> implements runnable

{

//body

}

Thread Class Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The microprocessor allocates memory tothe processes that we execute. Eachprocess occupies its own address space(memory). However all the threads in aprocess share the same address space.

• Therefore, resources like memory,devices, data of a program, andenvironment of a program are availableto all the threads of that program

• A thread is also known as “lightweightprocess” or “execution context”

Thread and Process

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• This is because there is fewer overloadson the processor when it switches fromone thread to another than it switchesfrom one process to another.

• Processes are therefore “heavyweight”process.

Thread and Process Cont.

Page 130: Ipu Java Notes

130

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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)

Processes Vs. Threads

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

New Ready

Blocked

Running

Done

Life Cycle of a Thread

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

wait

notify, timer, IO available

sleep

blocked for IO

Life Cycle of a Thread Cont.

Page 131: Ipu Java Notes

131

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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();

Life Cycle of a Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

aThread.start();• A call to start() will not immediately start

thread's execution but rather will move it topool of threads waiting for their turn to bepicked for execution.

• The thread scheduler picks one of the ready-to-run threads based on thread priorities.

Running• The thread code is being actively executed

by the processor. It runs until it is swappedout, becomes blocked, or voluntarily give upits turn with this static method

Life Cycle of a Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Thread.yield();Please note that yield() is astatic method. Even if it is called on anythread object, it causes the currentlyexecuting thread to give up the CPU.

Waiting• A call to java.lang.Object's wait() method

causes the current thread object to wait. Thethread remains in "Waiting" state until someanother thread invokes notify() or thenotifyAll() method of this object.

• The current thread must own this object'smonitor for calling the wait().

Life Cycle of a Thread Cont.

Page 132: Ipu Java Notes

132

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Sleeping• Java thread may be forced to sleep

(suspended) for some predefined time. Thread.sleep(milliseconds); Thread.sleep(milliseconds, nanoseconds);

Life Cycle of a Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Please note that static method sleep() onlyguarantees that the thread will sleep forpredefined time and be running some timeafter the predefined time has been elapsed.

• For example, a call to sleep(60) will causethe currently executing thread to sleep for 60milliseconds. This thread will be in ready-to-run state after that.

• It will be in "Running" state only when thescheduler will pick it for execution.

• Thus we can only say that the thread will runsome time after 60 milliseconds.

Life Cycle of a Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 abyte of data).

Blocked on Synchronization• A java thread may enter this state while

waiting for object lock. The thread will moveto Ready-to-Run when a lock is acquired.

Life Cycle of a Thread Cont.

Page 133: Ipu Java Notes

133

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Dead• A java thread may enter this state when it is

finished working. It may also enter this stateif the thread is terminated by anunrecoverable error condition.

Life Cycle of a Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Life Cycle of a Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Single threaded and Multithreaded

Page 134: Ipu Java Notes

134

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Multiple threads in a process run at thesame time, perform different tasks andinteract with each other.

• e.g. Microsoft internet explorer, is a webbrowser within browser, we can print apage in the background , while you arescrolling a page .You can play audio andwatch animated images at the same time.

• This behavior is close to real life whereyou perform several tasks concurrently.

Single threaded and Multithreaded Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The thread class• The java.lang.thread class is used to

construct and access individual threads in a multithreaded application.

Syntax:Access_specifier <class_name> extends

Thread{//body}

Single threaded and Multithreaded Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

OR

Access_specifier <class_name> implements runnable

{

//body

}

Single threaded and Multithreaded Cont.

Page 135: Ipu Java Notes

135

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A thread group is a data structure thatcontrols the state of a collection of threads asa whole.

• The sleep() method causes the thread fromwhich it is called to suspend execution for thespecified period of milliseconds.

• static void sleep(long milliseconds) throwsInterruptedException

The no of milliseconds to suspend isspecified in milliseconds.

Single threaded and Multithreaded Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• static void sleep(long millisecond,intnanoseconds)throws InterruptedException

• This is useful only in environments that allowtiming period as short as nanoseconds.

Single threaded and Multithreaded Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

setName()- set the name of a thread

getName()-obtain the name of a thread

final void setName(String ThreadName)

final String getName()

Where, ThreadName is the name of thread.

Single threaded and Multithreaded Cont.

Page 136: Ipu Java Notes

136

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Creating a ThreadIn the most general sense, you can create a

thread by instantiating an object of typeThread. Java defines two ways in which thiscan be accomplished:

• You can extend the Thread class, itself• You can implement the Runnable interface

Creating a Thread

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Extending Thread

• To create a thread, is to create a new classthat extends Thread, an then to create aninstance of that class. The extending classmust override the run() method, which is theentry point for the new thread.It must alsocall start() method to begin execution of thenew Thread.

Creating a Thread

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class NewThread extends Thread{NewThread(){

//create a new second ,Threadsuper("Demo Thread");System.out.println("Child Thread"+this);start();

}

Extending Thread

Page 137: Ipu Java Notes

137

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Extending Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Extend Thread Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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");}}

Extend Thread Cont.

Page 138: Ipu Java Notes

138

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Thread Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Implementing Runnable:To create a thread is to create a class that

implements Runnable interface. Runnableabstracts a unit of executable code.

• You can construct a thread on any object thatimplements Runnable.

• To implement Runnable, a class needs onlyimplement a single method called run(),which is declared like this:

public void run();

Implementing Runnable

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Inside run(), you will define the code thatconstitutes the new thread.

• run() can call other methods, use otherclasses, and declare variables, just like themain thread can.

• The only difference is that run() establishesthe entry point for another, concurrent threadof execution within your program. This threadwill end when run() returns.

Implementing Runnable Cont.

Page 139: Ipu Java Notes

139

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

After you create a class that implementsRunnable, you will instantiate an object oftype Thread from within that class.

Thread(Runnable threadob,String threadName)

• In this constructor, threadob is an instance ofa class that implements the Runnableinterface.This defines where execution of thethread will begin, the name of the new threadis specified by threadName.

Implementing Runnable Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• After the new thread is created, it will notstart running until you call its start() method,which is declared within Thread.

void strat() // it executes call to run

Implementing Runnable Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}

Implementing Runnable Cont.

Page 140: Ipu Java Notes

140

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// This is the entry point for the second threadpublic 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");}}

Implementing Runnable Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class ThreadDemo{public static void main(String f[]){new NewThread();//create a new threadtry

{for(int i=5;i>0;i--)System.out.println("main Thread"+i);Thread.sleep(1000);}

Implementing Runnablen Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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, yourprogram can spawn as many threads as it needs.

e.g. the following program creates three child threads:

Creating Multiple Threads

Page 141: Ipu Java Notes

141

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class NewThread implements Runnable{String name;// name of threadThread t;NewThread(String threadname){name=threadname;t=new Thread(this, name);System.out.println("New Thread"+":"+t);t.start(); //start the thread}

Creating Multiple Threads Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

Creating Multiple Threads Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Thread.sleep(10000);}

catch(InterruptedException e){System.out.println("main thread Interrupted");

}System.out.println("main thread exiting");

}}

Creating Multiple Threads Cont.

Page 142: Ipu Java Notes

142

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}

Creating Multiple Threads Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

catch(InterruptedException e)

{

System.out.println(name+"Interrupted");

}

System.out.println(name+"::"+"exiting");

}

}

Creating Multiple Threads Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• As you can see, once started, all three childthreads share the CPU. Notice the call tosleep()in main().This cause the main threadto sleep for ten seconds and ensures that itwill finish last.

• Using isAlive() and join()

Thread Methods

Page 143: Ipu Java Notes

143

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

There are two ways to determine whether athread has finished .

• First-You can call isAlive() on the thread.final boolean isAlive()The isAlive() method returns true if the threadupon which it is called is still running, itreturns false otherwise.

• Second-While isAlive() is occasionally useful,the method that you will more commonly useto wait for a thread to finish is called join()

Thread Methods Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

final void join() throws InterruptedException

• This method waits until the thread on which itis called terminates.

• Its name comes from the concept of thecalling thread waiting until the specifiedthread joins it.

Thread Method Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Synchronization

• When two or more threads need access to ashared resource, they need some way toensure that the resource will be used by onlyone thread at a time. The process by whichthis is achieved is called synchronization.

Synchronization

Page 144: Ipu Java Notes

144

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Monitor

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Sometimes one thread may be interested inthe activities of another. Or, one could havea 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

Inter-Thread Communication

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

final void wait()-tells the calling thread to giveup the monitor and go to sleep until someother thread enters the same monitor andcalls notify().

final void notify()- wakes up the first thread thatcalled wait() on the same object.

final void notifyAll()-wakes up all the threadsthat called wait() on the same object.

Inter-Thread Communication

Page 145: Ipu Java Notes

145

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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 synchronizedblocks, and they only effect other threads insynchronized blocks which are synchronized onthe same object.Note that you don’t 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.

Waiting for notification

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Deadlock

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

java.io (package)

• A collection of things wrapped or boxedtogether.

• A package is a namespace that organizes aset of related classes and interfacesConceptually you can think of packages asbeing similar to different folders on yourcomputer. You might keep HTML pages inone folder, images in another, and scripts orapplications in yet another.

Input/Output Programming

Page 146: Ipu Java Notes

146

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Because software written in the Javaprogramming language

• can be composed of hundreds or thousandsof 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.

Input/Output Programming Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• System.in (Object)- read input from the user.- Whatever the users types the return type

will always be a string because of the

wrapping.

Input/Output Programming Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Input/Output Programming Cont.

Page 147: Ipu Java Notes

147

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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 bytestreams. However, if you wanted to read instrings, you were in trouble, cause themethod to do that did not properly convertbytes to characters.

Input/Output Programming Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

IOException: Signals that an I/O exception ofsome sort has occurred. This class is thegeneral class of exceptions produced byfailed or interrupted I/O operations.

Input/Output Exception

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 consoleSystem.out.println(str);

} }

Input/Output Exception Example

Page 148: Ipu Java Notes

148

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Java defines two types of streams:

1. Byte

2. Character

• Byte stream provides a convenient meansfor handling input and output of bytes.

• It is used , when reading and writing binarydata.

Types Of Streams

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Character streams provides a convenientmeans for handling input and output ofcharacter.

• They use Unicode therefore , can beinternationalized.

• Also in some cases character streams aremore efficient than byte stream

Character Streams

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

There are 4 abstract classes for java.io that are very analogous to one another, but they do slightly different things.

§ Reader

§Writer

§ InputStream

§ OutputStream

Character Stream

Byte Stream

java.io Abstract Classes

Page 149: Ipu Java Notes

149

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Each of these abstract classes has severalconcrete subclasses, that handles thedifferences between the various devices,such as disk files, network connection andeven memory buffers.

• The above four abstract classes defineseveral key methods that the other streamclasses implements.Two most importantmethods are:

read(), and write()

java.io Abstract Classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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)

Character Stream

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Character Stream Cont.

Page 150: Ipu Java Notes

150

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Character stream classes through readingfrom and writing to a file:

• Character stream classes supports input andoutput for Unicode characters.

• The FileReader class allows to readcharacters from a file.

• FileWriter class allows you to write thecharacters to a file system.

Character Stream Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Byte Stream

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Byte stream classes through reading from andwriting to a file:

• Byte stream classes are used to create andmanipulate streams and files for reading and writingbytes.

• The FileInputStream class allows to read from a filein 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 towrite the output to a file system.

Byte Stream Cont.

Page 151: Ipu Java Notes

151

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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)

File handling

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

FileReader/Writer and FileInputStream/OutputStream

• In general use the readers and writers for text files,

• and streams for when you don’t 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

File Input and Output

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The File class is very useful for information about files and the directory structure.

• Constructer takes a String for the nameUseful methods:§ .exists()§ .isDirectory()§ .listFiles() - Lists the files if it’s a directory§ .canRead() / .canWrite() - check permissions§ File.listRoots() - returns an array of the roots of a file

system.§ .length()§ .delete()

java.io.File

Page 152: Ipu Java Notes

152

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Not a stream file.

• There is a file “pointer” which you can use toread and write to random place in the file.

• You can read and write only primitive datatypes - writeByte(), writeInt(), writeBoolean()

• It’s faster to jump between points in the file,than search an entire stream file.

java.io.RandomAccessFile

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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);

Sequence Input Stream

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

transient modifier: It is used when you do notwant to store certain data member to file.

class a

{

transient boolean b;// not to be stored

int i; //to be store

}

transient modifier

Page 153: Ipu Java Notes

153

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63 ‹#›

Network Programming and Java Sockets

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Introduction• Elements of Client Server Computing• Networking Basics• Understanding Ports and Sockets• Java Sockets§ Implementing a Server§ Implementing a Client

• Sample Examples• Conclusions

Agenda

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Difference between TCP/IP and UDP

Page 154: Ipu Java Notes

154

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Socket: It is used for transmission controlprotocol/Internet protocol (TCP/IP). The advantageof TCP/IP is the client can be any kind of computer.So all the computers in a network implementingTCP/IP can communicate with each other throughsockets.

• A socket is one end point of a two_waycommunication link between two programs runningon the network.

• The socket classes is used to represent theconnection between a client program and a serverprogram.

Socket

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The URL, URLConnection, Socket,ServerSocket classes are used TCP tocommunicate over the network.

• The DatagramPacket, DatagramSocket andMulticastSockets classes are used in UDP.

Note: Socket is not a physical device but anabstraction for the network software, thatenables communication between a serverand a client.

Socket Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

IP Address: The internet protocol (IP) providesevery network device with a logical addresscalled an IP address. It is represented as aseries of four 8 bit numbers. So, An IPaddress consists of 32 bit patterns eachrange is in the value from 0 to 255.

• In java InetAddress is a class under netpakage used for finding IP addresses. It hasthe following methods getLocalHost,getByName or getAllByName.

IP Address

Page 155: Ipu Java Notes

155

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

DNS: DNS is also used to identify the anyspecific host in the network.

It will give either name or 32 bit address“203.26.48.100”.

Port: data transmitted over the internet isaccompanied by addressing information thatidentifies the computer and the port for whichit is destined. The computer is identified by a32 bit IP address , which IP uses to deliverdata to the right computer in the networks.

DNS and Port

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Ports are identified by a 16 bit number, whichTCP and UDP use the port to deliver the datato the right application.

• The TCP/UDP protocols use ports to mapincoming data to a particular process runningon a computer.

• Port numbers ranges from 0 to 65535,because ports are represented by 16 bitnumbers. The port numbers ranges from 0-1023 are reserved for use by well knownservices. These ports are called well knownports.

Port Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Every protocol has a default port number,which is used if the port number is notspecified.

• Port is not a physical device but anabstraction to make communication betweena server and a client.

e.g.FTP 23SMTP 25

DOMAIN 53

HTTP 80 etc.

Port Cont.

Page 156: Ipu Java Notes

156

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java is a programming language for theinternet. It provides the package java.net fornetworking programs.

• Internet: It is a networks of network.It is amechanism for information dissemination,and a medium for collaboration andinteraction between individuals and theircomputers without regards for geographiclocations.

• Java supports two types of protocolsbasically: TCP/IP and UDP/IP.

Internet

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Internet and WWW have emerged as globalubiquitous media for communication andchanging the way we conduct science,engineering, and commerce.

• They also changing the way we learn, live,enjoy, communicate, interact, engage, etc. Itappears like the modern life activities aregetting completely centered around theInternet.

Internet Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Internet Server

PC client

Local Area Network

PDA

Internet Applications Serving Local and Remote Users

Page 157: Ipu Java Notes

157

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• To take advantage of opportunities presented bythe Internet, businesses are continuously seekingnew and innovative ways and means for offeringtheir services via the Internet.

• This created a huge demand for software designerswith skills to create new Internet-enabledapplications or migrate existing/legacy applicationson the Internet platform.

• Object-oriented Java technologies—Sockets,threads, RMI, clustering, Web services-- haveemerged as leading solutions for creating portable,efficient, and maintainable large and complexInternet applications.

Increased demand for Internet applications

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Network

a client, a server, and network

ClientServer

Client machineServer machine

Elements of C-S Computing

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Applications Layer§ Standard appsüHTTPüFTPüTelnet

§ User appsTransport Layer

§ TCP§ UDP§ Programming Interface:üSockets

Network Layer§ IP

Link Layer§ Device drivers

Application

(http,ftp,telnet,…)Transport

(TCP, UDP,..)

Network

(IP,..)

Link

(device driver,..)

Networking Basics

TCP/IP Stack

Page 158: Ipu Java Notes

158

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers.

Example applications:§ HTTP§ FTP§ Telnet

Application

(http,ftp,telnet,…)Transport

(TCP, UDP,..)

Network

(IP,..)

Link

(device driver,..)

Networking Basics Cont.

TCP/IP Stack

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Application

(http,ftp,telnet,…)Transport

(TCP, UDP,..)

Network

(IP,..)

Link

(device driver,..)

Networking Basics Cont.

TCP/IP Stack

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The TCP and UDPprotocols use portsto map incoming datato a particularprocess running on acomputer.

server

Port

ClientTCP

TCP or UDP

port port port port

app app app app

port# dataData

Packet

Understanding Ports

Page 159: Ipu Java Notes

159

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Port is represented by a positive (16-bit)integer value

• Some ports have been reserved to supportcommon/well known services:§ ftp 21/tcp§ telnet 23/tcp§ smtp 25/tcp§ login 513/tcp

• User level process/services generally useport number value >= 1024

Understanding Ports Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Sockets provide an interface for programmingnetworks at the transport layer.

• Network communication using Sockets is verymuch 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 programwritten in Java or non-Java socket program.

Sockets

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A server (program) runs on a specificcomputer and has a socket that is bound to aspecific port. The server waits and listens tothe socket for a client to make a connectionrequest.

serverClient

Connection requestpo

rt

Socket Communication

Page 160: Ipu Java Notes

160

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• If everything goes well, the server acceptsthe connection. Upon acceptance, the servergets a new socket bounds to a different port.It needs a new socket (consequently adifferent port number) so that it can continueto listen to the original socket for connectionrequests while serving the connected client.

server

ClientConnection

po

rt

port po

rt

Socket Communication Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A socket is an endpoint of a two-waycommunication link between two programsrunning on the network.

• A socket is bound to a port number so thatthe TCP layer can identify the application thatdata destined to be sent.

• Java’s .net package provides two classes:§ Socket – for implementing a client§ ServerSocket – for implementing a server

Sockets and Java Socket Classes

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

ServerSocket(1234)

Socket(“128.250.25.158”, 1234)

Output/write stream

Input/read stream

It can be host_name like “mandroo.cs.mu.oz.au”

Client

Server

Java Sockets

Page 161: Ipu Java Notes

161

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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() );

Implementing a Server

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

4. Perform communication with clientReceive 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.

}

Implementing a Server Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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();

Implementing a Client

Page 162: Ipu Java Notes

162

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// SimpleServer.java: a simple server programimport java.net.*;import java.io.*;public class SimpleServer {public static void main(String args[]) throws IOException

{// Register service on port 1234ServerSocket s = new ServerSocket(1234);Socket s1=s.accept(); // Wait and accept a connection// Get a communication stream associated with the socketOutputStream s1out = s1.getOutputStream();

A simple server Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

DataOutputStream dos = new DataOutputStream (s1out);// Send a string!dos.writeUTF("Hi there");// Close the connection, but not the server socketdos.close();s1out.close();s1.close();

}}

A simple server (simplified code)

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// SimpleClient.java: a simple client programimport java.net.*;import java.io.*;public class SimpleClient {public static void main(String args[]) throws IOException

{// Open your connection to a server, at port 1234Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234);// Get an input file handle from the socket and read the inputInputStream s1In = s1.getInputStream();DataInputStream dis = new DataInputStream(s1In);

A simple client (simplified code)

Page 163: Ipu Java Notes

163

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}}

(simplified code) Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 SimpleClientException 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)

Run

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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(); }

Socket Exceptions

Page 164: Ipu Java Notes

164

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

ServerSocket & Exceptions

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// 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 1234ServerSocket s = new ServerSocket(1234);while(true){

Socket s1=s.accept(); // Wait and accept a connection// Get a communication stream associated with the

socket

Server in Loop: Always up

© Bharati Vidyapeeth’s 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 socketdos.close();s1out.close();s1.close();

}}

}

Page 165: Ipu Java Notes

165

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

ServerThreads

Server ProcessClient 1 Process

Client 2 Process

n Internet

Multithreaded Server: For Serving Multiple Clients Concurrently

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Programming client/server applications inJava is fun and challenging. Programmingsocket programming in Java is much easierthan doing it in other languages such as C.

Conclusion

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Objective Type QuestionsQ.1Exceptions can be caught or rethrown to a calling method.(a) True(b) FalseQ.2 The subclass exception should precede the base class

exception when used within the catch clause.(a) True(b) FalseQ.3 Can a catch block exist without a try block?(a) Yes(b) No

Review Questions Cont.

Page 166: Ipu Java Notes

166

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Short Type QuestionsQ.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?

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Long QuestionsQ.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?

Review Questions Cont.

Page 167: Ipu Java Notes

167

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63 ‹#›

Event Handling

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 VideoJava AppletBeansSwingsServlets

Learning Objective

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• All the various types of AWT events, areplaced in a separate package calledjava.awt.event for the sake of convenience.

• The Abstract Window Toolkit (AWT) isJava's original platform-independentwindowing, graphics, and user-interfacewidget toolkit. The AWT is now part of theJava Foundation Classes (JFC) — Thestandard API for providing a graphical userinterface (GUI) for a Java program.

AWT Introduction

Page 168: Ipu Java Notes

168

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

AWT Introduction

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

6.The interface to input devices such as mouse andkeyboards.

7.The AWT Native Interface, which enables renderinglibraries compiled to native code to draw directly toan AWT Canvas object drawing surface.

8. Access to the system tray on supporting systems9.The ability to launch some desktop applications

such as web browsers and email clients from aJava application

AWT Introduction

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

AWT- It is a package that contains classes, which are used tocreate interfaces and in event handling.

Java.awt (package)

Component

Label Button Container Text Component

Window

Frame

Panel

TextField TextArea

AWT Definition

Page 169: Ipu Java Notes

169

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A component is an object that can bedisplayed on the screen and can interact withthe user.

• It is like a button or scroll bar that has visualrepresentation in a screen window. It hasspecial property like background color andfont color.

Component Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Component is an abstract class thatencapsulate all of the attributes of a visualcomponent.

• All user interface elements that are displayedon the screen and that interact with the userare subclasses of “Component”.

• A component object is responsible forremembering the current foreground andbackground colors and the currently selectedtext font.

Component

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Container:- It is a subclass of Componentclass. It has additional methods that allowother Component objects to be nested withinit. Other Container objects can be storedinside of a Container (since they arethemselves instance of Component). It usesvarious Layout Managers.

Container

Page 170: Ipu Java Notes

170

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Panel:- It is a concrete subclass of a Container.It doesn’t add any new methods; it simplyimplements 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 atitle bar, Menu bar, or border.

Panel

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• When you run an applet using an appletviewer, the applet viewer provides the titleand border.

• Other components can be added to a panelobject by its add() method. (inherited fromcontainer).

• Once these components have been added,you can position and resize them manuallyusing the setLocation(), setSize(), orsetBounds() methods defined by Component.

Panel Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Window:- The window class creates a top-levelwindow.

• A top-level window is not contained withinany other object; it sits directly on thedesktop.

• Generally we won’t create window objectsdirectly, instead will use a subclass ofWindow called Frame.

Windows

Page 171: Ipu Java Notes

171

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Frame:- sub class of a Window .• It has a title bar, menu bar, borders, and

resizing corners.

• When a Frame window is created by aprogram a normal window is created (ratherthan an applet).

Frame

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Canvas:- Although it is not part of the hierarchy forapplet or frame window, there is one another typeof window called Canvas.

• Canvas encapsulates a blank window upon whichyou can draw.

Canvas

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Buttons

Common buttons

Radio buttons

Check buttons

GUI components

Page 172: Ipu Java Notes

172

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

GUI components• Combo boxes• Lists• Menus

GUI components

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Spinners

• Sliders

• Textfields

GUI components

© Bharati Vidyapeeth’s 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 (orevents) is called an “Event Source”.

i.e. a source is an object that generates anevent.

Page 173: Ipu Java Notes

173

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A source must register listeners in order forthe listeners to receive notifications about aspecific type of event. Each type of event hasits own registration method.

• The methods that add or remove listenersare provided by the source that generatesevents.

Delegation Event Model

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Any object that is interested in receivingmessages (or events ) is called an “EventListener”.

i.e. A listener is an object that is notifiedwhen an event occurs.

Delegation Event Model

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

It has two major requirements:

1. It must have been “registered” (add) withone or more sources to receivesnotifications about specific types of events.

2. It must “implement” methods to receive andprocess these notifications.

Delegation Event Model

Page 174: Ipu Java Notes

174

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

According to Sun, the reasons for comingout with the Java 1.1 Delegation EventModel are:

1. A source generates an event and sends itto one or more listeners.

2. In this scheme, the listener simply waitsuntil it receives an event.

3. Once received, the listener processes theevent and then return.

Delegation Event Model

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

4. The advantage of this design is that theapplication logic that processes events iscleanly separated from the user interfacelogic that generates those events.

5. A user interface element is able to“delegate” the processing of an event to aseparate piece of code.

Delegation Event Model

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

6. In this event model, listener must registerwith a source in order to receive an eventnotification. This provide an importantbenefit: notification are sent only to listenersthat want to receive them.

7. This is a more efficient way to handle eventsthan the design used by the old java 1.0approach.

Delegation Event Model

Page 175: Ipu Java Notes

175

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Old java 1.0 approach:- an event waspropagated up the containment hierarchyuntil it was handled by a component. Thisrequired components to receive events thatthey did not process, and it wasted valuabletime.

Note: The delegation model eliminates thisoverhead.

8. Facilitate the creation of robust eventhandling code which is less error-prone(strong compile-time checking)

Delegation Event Model

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Methods of component class-1. 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)

Methods of component class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Steps for creating GUI:

• Create object of container

• Create objects of control

• Customize appearance of container andcontrols

• Add controls on container

• Show container

Steps for creating GUI

Page 176: Ipu Java Notes

176

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Events: In the delegation model, an event is anobject that describes a state change in asource.

• Some of the activities that cause events to begenerated are “pressing a button”, “entering acharacter via the keyboard”, “selecting anitem in a list”, and “clicking the mouse”, etc.

Events

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Events may also occur that are not directlycaused by interactions with a user interface.

e.g. an event may be generated when “atimer expires”, “a counter exceeds a value”,“a software or hardware failure occurs”, or“an operation is completed”, etc.

Events Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Event Delegation Model is based on fourconcepts:

1. The Event Classes2. The Event Listeners3. Explicit Event Enabling4. Adapters

Event Delegation Model is based on four concepts

Page 177: Ipu Java Notes

177

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• At the root of the java event class hierarchyis 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 ofthe event.

toString()- returns the string equivalent of theevent.

Event Delegation Model is based on four concepts

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

ActionEvent generated by component activationAdjustmentEvent generated by adjustment of adjustable components

such as scroll barsContainerEvent generated when components are added to or removed

from a containerFocusEvent generated when a component receives input

focusItemEvent generated when an item is selected from a list,

choice or check boxKeyEvent generated by keyboard activityMouseEvent generated by mouse activityPaintEvent generated when a component is paintedTextEvent generated when a text component is modifiedWindowEvent generated by window activity like minimizing or

maximizing

1. Event Class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Listeners for Different Events

• For each event type that can occur, theapplication can add event listeners, that havemethods invoked when the event occurs.

• The listeners are defined as interfaces, sothat an actual listener has to implement thesemethods.

2. Event Listener

Page 178: Ipu Java Notes

178

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The names of the listener classes are simplyderived from the names of the events theyhandle,

• MouseEvent's have two different types oflistener for efficiency reasons.(MouseListener and MouseMotionListener)

2. Event Listener

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Listener- Compare and matches the applicationwith its event. Every listener in java is aninterface .Hence, need to implement.

Steps:

1. Create a Listener class.

2. Give body to all the methods of listenerInterfaces.

3. Register the control on which the event isgenerated. (b.addActionlistner(this))

Event Handling Steps

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• An event listener may be removed from anEvent Source's list of interested Listeners bycalling a remove...Listener() method, passingin the listener object to be removed.

• For example, in the above code fragment,the code below removes the action listenerobject listenerObject from the buttonm_Button.

m_Button.removeActionListener( listenerObject );

Event Handling Steps Cont.

Page 179: Ipu Java Notes

179

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Any number of event listener objects canlisten for all kinds of events from any numberof event source objects.

e.g. a program might create one listener perevent source or a program might have asingle listener for all events from

all sources.

Listeners

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Multiple listeners can register to be notified ofevents of a particular type from a particularsource.

• Also, the same listener can listen tonotifications from different objects.

Listeners

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Each type of listeners can be notified only forits corresponding types of events which canbe generated by specific types of sources.

Listeners

Page 180: Ipu Java Notes

180

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Many buttons can register the same listenersince all buttons generate the same type ofevent. This type of event may be generatedby other types of sources as well.

button1

ListItem3

button2

ActionListener

Multiple sources, single listener

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A single source may generate different typesof events and thus register multiple listeners.

MouseMotion Listener

MouseWheel ListenerMouseWheelEvent

Single source, multiple listeners

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• You implement an interface to create alistener.

• In the case of a single source that generatesmultiple types of events you can create asingle listener that implements all interfaces(remember: a class may extend only onesuperclass but implement more than oneinterfaces).

Listeners as interfaces

Page 181: Ipu Java Notes

181

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

MouseMotion Listener

MouseWheel Listener MouseWheelEvent

MouseWheel + MouseMotion Listener

Single source, multiple listeners again

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

To handle an event you need 3 steps:

§ Implement the appropriate interface thatwill produce your listener class.

§ Create a listener object.

§ Register the listener to the source ofinterest.

Event handling steps

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

• You can find the source of an event by usingthe getSource method:event_object.getSource();

Putting it into code

Page 182: Ipu Java Notes

182

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Event Listener MethodActionEvent ActionListener actionPerformed()AdjustmentEvent AdjustmentListener adjustmentValueChangd()ComponentEvent ComponentListener componentResized()

componentMoved()componentShown()componentHidden()

FocusEvent FocusListener focusGained()focusLost()

ItemEvent ItemListener itemStateChanged()KeyEvent KeyListener keyTyped()

keyPressed()keyReleased()

Listeners for Each Event

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

MouseEvent MouseListener mouseClicked()mouseEntered()mouseExited() mousePressed()mouseReleased()

MouseMotionListenermouseDragged()mouseMoved()

WindowEvent WindowListenerwindowClosed()windowClosing()windowDeiconified()windowIconified()windowOpened()

Listeners for Each Event

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The following table lists which objects can have which listener types added:

GUI Object ListenerButton ActionListenerChoice ItemListenerCheckbox ItemListenerComponent ComponentListener

FocusListenerKeyListenerMouseListenerMouseMotionListener

Dialog WindowListener

Listeners for Object

Page 183: Ipu Java Notes

183

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Frame WindowListenerList ActionListener,ItemListenerMenuItem ActionListenerScrollbar AdjustmentListener

TextField ActionListener

Note that every GUI object that inherits from Component can have Component, Focus, Key, Mouse and MouseMotion listeners added.

Listeners for Each Event

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Action Events

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Item events are generated for the following objects: GUI Object ActionChoice Click on itemCheckbox Select an item

Deselect an itemList Select an item

Deselect an itemExtend a selection

Reduce a selection

Item Events

Page 184: Ipu Java Notes

184

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A subclass can handle its own events byadding itself as a listener.

• In Explicit Event Handling, you control theorder.

3. Listeners vs. Explicit Enabling Event

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java provides adapter classes thatimplements the corresponding listenerinterface containing more than one method.

• The methods in the classes are empty. Thelistener class that you define can extend theAdapter class and override the methods thatyou need.

4. Adapter class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Adapter classes are fully “abstract classes”that correspond to listener interfaces.

• They are “extended” (not implemented) andthus you can ignore methods that do notinterest you.

• You can use them “instead of listeners” in thecase that only some of the methods of theinterface are to be used.

Adapter classes Cont.

Page 185: Ipu Java Notes

185

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• You don’t use the “abstract specifier” and of course you cannot use “multiple inheritance”.

Some adapter classes:

§ KeyAdapter (instead of KeyListener)

§MouseAdapter (MouseListener)

§MouseMotionAdapter (MouseMotionListener) etc…

Adapter classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Event listeners often define many methods.

• Since they are interface, you must implementall of them.

• Alternative: Subclass an appropriate adapterand override only the one you need.

Adapter classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Adapter Class Listener Interface

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

FocusAdapter FocusListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

WindoAdapter WindowListener

Adapter Classes

Adapter classes Cont.

Page 186: Ipu Java Notes

186

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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));

}}

Adapter classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

class MyMouseAdapter extends MouseAdapter {MouseAdapterDemo mad;

public MyMouseAdapter(MouseAdapterDemo mad) {this.mad = mad;

}

public void mousePressed(MouseEvent me) {mad.setBackground(Color.red);mad.repaint();

}

Adapter classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}}

Adapter classes Cont.

Page 187: Ipu Java Notes

187

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

There are three methods of event handling:-

1. Outer class

2. Inner class

3. Same class

Methods of event Handling

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Notes:: Inner classes also called nestedclasses and these are declared within otherclasses.

• The program that are not named within aprogram are called anonymous class.

• An anonymous class cannot have aconstructor as the class has no name.

Anonymous Class

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• You may create all different classesindependently and put them in separate files.

• you can implement your listeners inside theclass that extends your Frame, making it an“inner class”.

• This enables you to put everything in oneclass (and hence in one file).

Inner classes

Page 188: Ipu Java Notes

188

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

import java.applet.*;import java.awt.*;import java.awt.event.*;/*<applet code="MouseInnerDemo"

width=100 height=100></applet>

*/public class MouseInnerDemo extends Applet {

Inner Classes

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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();} }}

Inner Classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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();

}

Anonymous Inner Classes

Page 189: Ipu Java Notes

189

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}

});}

}

An An Anonymous Inner ClassAnonymous Inner Class

Anonymous Inner Classes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

What is the difference between a GUI and a console app?

From the programmer’s perspective?

• A console app enables interaction through aspecified “flow” of I/Os.

• A GUI app makes it much more flexible. Theuser is allowed to perform combinations ofactions.

Console vs. GUI applications

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Class Framejava.lang.Object

java.awt.Component

java.awt.Container

java.awt.Window

java.awt.Frame

Working with Windows

Page 190: Ipu Java Notes

190

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A Frame is a top-level window with a title anda border.The size of the frame includes any areadesignated for the border. The dimensions ofthe border area may be obtained using thegetInsets method, however, since thesedimensions are platform-dependent, a validinsets value cannot be obtained until theframe is made displayable by either callingpack or show. Since the border area isincluded in the overall size of the frame, the

Working with Frame Windows Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

border effectively obscures a portion of theframe, constraining the area available forrendering and/or displaying subcomponentsto the rectangle which has an upper-leftcorner location of (insets.left, insets.top), andhas a size of width - (insets.left + insets.right)by height - (insets.top + insets.bottom).

• The default layout for a frame isBorderLayout.

Working with Frame Windows Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Frame() //creates a standard window that does not contain a title.

Frame(String title) //creates a window with the title specified by title.

MethodsSetting the windows dimensionvoid setSize(int w,int h);Hiding and Showing a windowsetVisible(boolean flag)Setting a window titlevoid setTitle(String str)Closing a frame windowsetVisible(false)

Working with Frame Windows Cont.

Page 191: Ipu Java Notes

191

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Frame:

• Frame()-

• Frame(String)-

• Frame f=new Frame(calculator);

• setTitle(String), f.setTitle(“Calculator”)

• getTitle(String)

• setLayout(null)

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Label -is a control that is used for displayingmessages or output.

1.Label()

2.Label(String)

• Label l= new Label()

• l.setText(“”)

• l.getText()

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

TextField- is a control used for single lineinput.

1. TextField()

2. TextFieldl(String)

• setText() & getText()

Working with Frame Windows

Page 192: Ipu Java Notes

192

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Button

• Button b=new Button(“ok”)

• Method-

• b.setLabel(String)

• b.getLabel(String)

Working with Frame Windows

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Working with Windows

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

java.lang.Object java.awt.Graphics public abstract class Graphics extends Object

The Graphics class is the abstract base class for all graphicscontexts that allow an application to draw onto componentsthat are realized on various devices, as well as onto off-screen images.

(public class ObjectClass 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.)

Working with Graphics

Page 193: Ipu Java Notes

193

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

drawLinepublic 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 coordinatesystem.

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

Drawing Lines

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

}}

Drawing Lines Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

drawRectpublic 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. Thetop and bottom edges are at y and y + height. Therectangle is drawn using the graphics context's currentcolor.

§ 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

Drawing Rectangles

Page 194: Ipu Java Notes

194

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

fillRectpublic 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 andbottom edges are at y and y + height - 1. The resultingrectangle covers an area width pixels wide by heightpixels tall. The rectangle is filled using the graphicscontext'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.

Drawing Rectangles Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

}}

Drawing Rectangle Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

drawRoundRectpublic 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 areat x and x + width, respectively. The top and bottom edges of therectangle 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.

Drawing Rounded Rectangle

Page 195: Ipu Java Notes

195

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

fillRoundRectpublic 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 areat x and x + width - 1, respectively. The top and bottomedges 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.

Drawing Rounded Rectangle Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

}}

Drawing Rounded Rectangle Example.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Drawing Oval Example.

Page 196: Ipu Java Notes

196

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Fill Oval Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

drawArcpublic 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 atstartAngle and extends for arcAngle degrees, using thecurrent color. Angles are interpreted such that 0 degreesis at the 3 o'clock position. A positive value indicates acounter-clockwise rotation while a negative valueindicates a clockwise rotation.

§ The center of the arc is the center of the rectangle whoseorigin is (x, y) and whose size is specified by the widthand height arguments.

§ The resulting arc covers an area width + 1 pixels wide byheight + 1 pixels tall.

Draw Arc Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Draw Arc Example Cont.

Page 197: Ipu Java Notes

197

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

fillArcpublic 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 andextends for arcAngle degrees. Angles are interpretedsuch that 0 degrees is at the 3 o'clock position. A positivevalue indicates a counter-clockwise rotation while anegative value indicates a clockwise rotation.

§ The center of the arc is the center of the rectangle whoseorigin is (x, y) and whose size is specified by the widthand height arguments.

§ The resulting arc covers an area width + 1 pixels wide byheight + 1 pixels tall.

Fill Arc Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

§ The angles are specified relative to the non-squareextents of the bounding rectangle such that 45 degreesalways falls on the line from the center of the ellipse tothe upper right corner of the bounding rectangle. As aresult, if the bounding rectangle is noticeably longer inone axis than the other, the angles to the start and end ofthe arc segment will be skewed farther along the longeraxis 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.

Fill Arc Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Draw String Example

Page 198: Ipu Java Notes

198

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Text stringsYou already met the instruction used todisplay strings on the screen. In case youdidn't, you won't be surprised to hear that it isdrawString. Just to remind you - a string is apiece of text, anything from a singlecharacter (a term which includes letters,punctuation, symbols such as @ or ^, andeven the space character) to a wholesentence. Strings are specified by placingthem within double quotation marks.

Draw String Example Cont

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The method drawString is given three parametersbetween brackets. The first item is the string itselfto be displayed on the screen. The other twonumbers specify where the string is to appear. Itrepresents the top-left corner of the string.However, the second number actually specifies they-co-ordinate of a line on which the text sits. Somecharacters, such as 'g' or 'y' will drop down belowthis imaginary line, as shown in the followingexample:

g.drawString("This is hugely easy",40,60);

Draw String Example Cont

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Working with colors

Page 199: Ipu Java Notes

199

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

American spelling of 'Color'). It expects to begiven a colour name, but the colour namemust be of a standard type specified in yetanother class called Color. What all thismeans is that colours are chosen as follows:

g.setColor(Color.blue);g.setColor(Color.orange);

Working with colors Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Here are the thirteen standard colours. Makesure you use them exactly as specified -don't alter the case of the letters or insertspaces in the middle of them, and note thespelling of 'Gray'.

Black Gray Orange Yellow BlueGreen Pink Cyan lightGray ReddarkGray Magenta white

Working with colors Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Any colour that you choose will then be usedfor drawing all lines, text, shapes and as thefill-in colour for shapes until you chooseanother colour. You can also determine thecolour of the background to the applet. Thisis done using the following instruction:

setBackground(Color.cyan);

Again, like the setColor method, it isimportant to note that the name of themethod is all lower case letters except for the

Working with colors Cont.

Page 200: Ipu Java Notes

200

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

capital B in the middle. However, please notethat setBackground is not part of the graphicsenvironment, and as such, does not need tobe preceded by g. In fact, if you do put g. atthe beginning, then the Java compilercomplains. I have fallen into this trap manytimes!

Working with colors Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

repaintOccasionally, there will be points in the

program where you will want it redraw thescreen. Perhaps the screen has changed(the paint method can easily cope with ifstatements that get it to draw different thingsin different circumstances). To call the paintmethod in these circumstances, use thefollowing instruction:

Working with repaint()

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

repaint(); Note that there are no parameters(no numbers, strings or graphicsenvironments) passed to this method, butyou still must include the two brackets andfollow them with the obligatory semicolon,like this ();

It is vital that you don't include this methodinside the paint method itself. If you did, thepaint method would never terminate, as itwould always be calling itself.

Working with repaint()0.

Page 201: Ipu Java Notes

201

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Controls are components that allows a user tointeract with your application in various ways- e.g. acommonly 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 editingThese controls are subclass of Component.

Using AWT Controls

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Adding and Removing ControlsTo 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

Using AWT Controls Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Responding to controls Except for Labels, which are passive controls, all controls

generate events when they are accessed by the user.

LabelsA label is an object of type Label.Label()Label(String str)Label(String str, int how)

Where Label.LEFT, Label.RIGHT, Label.CENTER

Using AWT Controls Cont.

Page 202: Ipu Java Notes

202

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

ButtonsA 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)

Using AWT Controls Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Choice and ListEvent- ItemEvent

Listener- ItemListener

Method- public void ItemStateChanged(ItemEvent e)

Register- addItemListener(ItemListener)

Using AWT Controls Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Scrollbar (horizontal/vertical)Event- AdjustmentEvent

Listener- AdjustmentListener

Method- public void AdjustmentValueChanged(AdjustmentEvent e)

Register- addAdjustmentListener(ItemListener)

Using AWT Controls Cont.

Page 203: Ipu Java Notes

203

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

CheckBox- Multiple Selection

checkBox(String)

e.g. checkBox c=new CheckBox(string);

checkBox(string,Boolean)

e.g. checkBox c1=new CheckBox(study,true);

Using AWT Controls Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

Using AWT Controls Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

You use layout managers to design your GUIs.

There are several managers like:

§ FlowLayout

§ BorderLayout

§ GridLayout

§ CardLayout

§ GridBagLayout

Layout Managers

Page 204: Ipu Java Notes

204

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Default layout

• Components laid out from the top-left corner, from left to right and top to bottom like a text.

FlowLayout

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Places components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area

BorderLayout

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Simply makes a bunch of componentsequal in size and displays them in therequested number of rows and columns

GridLayout

Page 205: Ipu Java Notes

205

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

CardLayout

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• is a sophisticated, flexible layout manager. Italigns components by placing them within agrid of cells, allowing some components tospan more than one cell.

GridBagLayout

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Putting it into code:§ Setting the manager:Container myCont = getContentPane();myCont.setLayout(new FlowLayout());

§ Adding Components:myCont.add(aComponent, BorderLayout.WEST);

Layout Managers Code

Page 206: Ipu Java Notes

206

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The java.awt.Image class is actually abstract.However, methods such as getImage(URL)in the Applet class return an instance of aconcrete subclass provided by the particularJVM implementation. The details of thatsubclass are not important since you invokeonly methods listed in the Image class, manyof which are overridden by the subclass.

Handling Image

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Image class provides only minimal access toinformation about the image. It does include themethods

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 contextobject via the Image class method

Graphics getGraphics ()You then invoke the usual drawing methods in the

Graphics object to draw on the image.

Handling Image Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Handling Image Cont.

Page 207: Ipu Java Notes

207

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Threads and Animation

The only functions we have seen in applets sofar are init(), paint(), and functions called inresponse to input events. All of thesefunctions are supposed to do a small amountof work and return quickly. There has beenno opportunity, so far, for a function to loopand do some continuous work.

Animation

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

This applet creates a thread, a separatestream of execution, to perform abackground task. The body of the thread'scode is in the run() function. In this case, thepurpose of the thread is to increment thevariable i once every 1000 milliseconds, andcause the applet to redraw itself. The result isa simple animation.

Animation Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

import java.applet.*;import java.awt.*;

public class Threads1 extends Applet implements Runnable {

int width, height;int i = 0;Thread t = null;boolean threadSuspended;

Animation Cont.

Page 208: Ipu Java Notes

208

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// 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()");}

Animation Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// 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();

}

Animation Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

else {if ( threadSuspended ) {

threadSuspended = false;System.out.println("start(): notifying thread");synchronized( this ) {

notify();}

}}System.out.println("start(): end");

}

Animation Cont.

Page 209: Ipu Java Notes

209

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Animation Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

// Now the thread checks to see if it should suspend itselfif ( 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");}

Animation Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

}

}

Animation Cont.

Page 210: Ipu Java Notes

210

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Java Media Framework API (JMF)enables audio, video and other time-basedmedia to be added to applications andapplets built on Java technology. Thisoptional package, which can capture,playback, stream, and transcode multiplemedia formats, extends the Java 2 Platform,Standard Edition (J2SE) for multimediadevelopers by providing a powerful toolkit todevelop scalable, cross-platform technology.

Sound And Video

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

APPLET

• An Applet is Loaded into a java-enabledprogram (Netscape, Applet Viewer)

• Applet is not a stand-alone program (no mainmethod), structured to run inside anotherprogram (browser)

• JVM runs applications, but not applets. Anapplet can run as an application if it defines amain().

• Applets are usually event-driven.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Does I/O through a GUI, only displays errormessages with stdout.

• Applets subclass java.applet

• Security - applets barred from reading/writingfiles on the client,can’t load libraries, can’tmake network connections (except to itshost), can’t execute programs, etc...

APPLET Cont.

Page 211: Ipu Java Notes

211

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Applet lifecycle: (methods overridden from Applet class):

init(), start(), paint(g),stop(), destroy()

Loading an applet

§ an instance of the applet’s controlling class (Applet subclass) created

§ applet initializes itself

§ applet starts running

APPLET Life Cycle

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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)

APPLET Life Cycle Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java Bean is a developed by SunMicrosystems that defines how Java objectsinteract.

• An object that conforms to this specificationis called a JavaBean, and is similar to anActiveX control.

• It can be used by any application thatunderstands the JavaBeans format.

Bean

Page 212: Ipu Java Notes

212

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The principal difference between ActiveXcontrols and JavaBeans are that ActiveXcontrols can be developed in anyprogramming language but executed only ona Windows platform, whereas JavaBeanscan be developed only in Java, but can runon any platform.

Bean Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• A java bean is a software component that has beendesigned to be reusable in a variety of differentenvironment.

• It may perform a simple function , such as checkingthe 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 datapoints is an example of a Bean that can executelocally.

Bean Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Advantage• A software component architecture provides

standard mechanism to deal with softwarebuilding blocks:

• A bean obtain all the benefits of java’s “write-once, run-anywhere” paradigm.

• The properties, events, and method of aBean that are exposed to an applicationbuilder tool can be controlled.

Page 213: Ipu Java Notes

213

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Java beans are a framework for creatingcomponents in Java.

• AWT and Swing packages are built withinthis framework

• Made to fit in with graphic developmentenvironments such as Jbuilder and Forte.

• An extension is Java Enterprise Beans

Java Beans

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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. implementserializable

Bean Rules

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Introspection used to asses what a bean cando (which methods it has)

• There is also an interface BeanInfo to givedevelopment tools more information

• Tools can change a bean’s properties, e.g.background color in a window if the windowis regarded as a bean.

Java Beans: Development Environments

Page 214: Ipu Java Notes

214

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

We learned that JavaBeans are Java classeswhich adhere to an extremely simple codingconvention. All you have to do is toimplement java.io.Serializable interface, usea public empty argument constructor andprovide public getter and setter methods toget and set the values of private variables

( properties ).

Summary

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Swing is a widget toolkit for Java. It is part ofSun Microsystems' Java Foundation Classes(JFC) — an API for providing a graphicaluser interface (GUI) for Java programs.

Swing was developed to provide a moresophisticated set of GUI components thanthe earlier Abstract Window Toolkit.

Swing

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Java Swing provides the multipleplatform independent APIs interfaces forinteracting between the users and GUIscomponents. All Java Swing classes importsform the import javax.swing.*; package. Javaprovides an interactive features for designthe GUIs toolkit or components like: labels,buttons, text boxes, checkboxes, comboboxes, panels and sliders etc. All AWTflexible components can be handled by theJava Swing.

Swing Cont.

Page 215: Ipu Java Notes

215

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Java Swing supports the pluggingbetween the look and feel features. The lookand feel that means the dramaticallychanging in the component like JFrame,JWindow, JDialog etc. for viewing it into theseveral types of window.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

Above code sets the operation of close operation toExit the application using the System exit method.

Swing Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

}}

Creating a frame by usingSwing

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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);

} }

OR Creating a frame by using Swing

Page 216: Ipu Java Notes

216

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

ServletWhy Java Servlets Instead of CGI?

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The advantages of using servlets is their fastperformance and ease of use combined withmore power over traditional CGI. TraditionalCGI scripts written in Java have a number ofdisadvantages when it comes toperformance. When a HTTP request is madea new process is created for each call of theCGI script. This overhead of process creationcan be very system intensive especiallywhen the script does relatively fast

Advantages

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

operations (process creation will take moretime than CGI script execution). Java servletssolve this problem by allowing each requestto be handled by a separate Java threadwithin the Web server process, omittingseparate process forking by the HTTPdaemon. In addition, simultaneous CGIrequest causes the CGI script to be copiedand loaded into memory as many times asthere are requests. However with servletsthere are same amount of threads as requestbut there will only be one copy of the servletclass created in memory.

Advantages Cont.

Page 217: Ipu Java Notes

217

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

Servlet Structure

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Web App with Servlets

HEADERS

BODY

Servlet

doGet()……

GET …

Servlet Container

Servlet Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

5 Simple Steps for Java Servlets1. Subclass off HttpServlet2. Override doGet(....) method3. HttpServletRequest§ getParameter("paramName")

4. HttpServletResponse§ set Content Type§ get PrintWriter§ send text to client via PrintWriter

5. Don't use instance variables

Servlet Cont.

Page 218: Ipu Java Notes

218

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Servlet Lifecycle

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• On each request, the server spawns a newthread and calls service()

• service() checks HTTP request type andcalls appropriate doXXXX (Get, Post, Put...)

• don't override service (unless you reallyknow what you're doing)

Servlet Cycle Cont.

(Service Method)

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

In this chapter, you learnt about Java eventsand the delegation event model necessaryto support them. More specifically, youlearned about Java events, including theevent listener capable of generating themand how they are handled by the Java AWTlibrary. You saw examples of using theswings that are more useful in eventhandling and a Java Servlet is an efficient,convenient, powerful, portable, secure,inexpensive that’s why it is more useful.

Summary

Page 219: Ipu Java Notes

219

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Event-driven programming provides the means todevelop flexible applications where the userdetermines program flow. Implementing eventhandlers in Java is generally straightforward, but it'simportant to know which approach is best for whichsituation. In this article, we looked at three of themost common ways to implement event handling:dispatching events to an object, using ananonymous class to dispatch an event directly tothe method that handles it, and using reflection towrite a generic class that dispatches events to theevent handler method.

Conclusion

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Objective type QuestionsQ1) The CheckboxGroup class is a subclass of the Component

class.(a)True(b)FalseQ2) You want to construct a text area that is 80 character-

widths wide and 10 characters height tall.what code do youuse?

(a) New TextArea(80,10)(b) New TextArea(10,80)

Review Questions

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Q3)Which of the following are direct or indirect subclasses ofcontainer

(a)Frame(b)TextArea©MenuBar(d)FileDialog(e)AppletQ4)Which method will cause a frame to be displayed(a)show()(b)setVisible()©display()(d)DisplayFrame()

Review Questions Cont.

Page 220: Ipu Java Notes

220

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Q5)Which method is method to set the layout of a container

startLayout()

initLayout()layoutContainer()setLayout()

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Short QuestionsQ1)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?

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Long QuestionsQ1)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 organizedQ4)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?

Review Questions Cont.

Page 221: Ipu Java Notes

221

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63 ‹#›

Unit-IV

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Overview of Internet and Intranet Services

• HTML Tags

• Tables

• Frames

• Graphical and animation techniques

• Static & Dynamic Web Pages

• DHTML

• ASP

• Javascript

Learning Objectives

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The Internet, sometimes called the"Information Superhighway", is a worldwide,publicly accessible series of interconnectedcomputer networks that transmit data (bypacket switching) using the standard InternetProtocol (IP).

• It is a "network of networks" that consists ofmillions of smaller domestic, academic,business, and government networks, whichtogether carry various information andservices, such as electronic mail, online chat,file transfer, and the interlinked web pages).

Overview of Internet and Intranet Services

Page 222: Ipu Java Notes

222

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

and other resources of the World Wide Web(WWW

• The Internet is a collection of interconnectedcomputer networks, linked by copper wires,fiber-optic cables, wireless connections, etc.

• In contrast, the Web is a collection ofinterconnected documents and otherresources, linked by hyperlinks and URLs.

• The World Wide Web is one of the servicesaccessible via the Internet, along with variousothers including e-mail, file sharing, onlinegaming,etc.

Overview of Internet and Intranet Services Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• An intranet is a private computer network that usesInternet protocols and network connectivity tosecurely share part of an organization's informationor operations with its employees.

• Sometimes the term refers only to the most visibleservice, the internal website. The same conceptsand technologies of the Internet such as clients andservers running on the Internet protocol suite areused to build an intranet. HTTP and other Internetprotocols are commonly used as well, such as FTP.

Overview of Internet and Intranet Services Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• An intranet is an information portal designedspecifically for the internal communications ofsmall, medium or large businesses,enterprises, governments, industries orfinancial institutions of any size or complexity.Intranets can be custom-designed to fit theexact needs of businesses no matter wherethey are situated. Users of intranets consistsmainly 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..

Overview of Internet and Intranet Services Cont.

Page 223: Ipu Java Notes

223

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

An extranet is somewhat very similar to anintranet. Extranets are designed specificallyto give external, limited access to certain filesof your computer systems to:

1. Certain large or privileged customers.2. Selected industry partners.3. Suppliers and subcontractors... etc.

Extranet

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Advantages :• Communication• Information• Entertainment• Services (online banking, job seeking,

purchasing tickets for your favorite movies,guidance services, etc. )

• E-Commerce (business deals, that involvesthe transfer of information across the globevia Internet ),etc.

Advantage & Disadvantage

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

DisadvantagesTheft of Personal information

• Spamming –Email spamming is when peoplesend out large batches of emails (mail shots)to unknown recipients. This is similar to 'junkmail' you get through the post. Search enginespamming is used by people trying toimprove their rankings by repetitive use ofkeywords and submissions.

• Virus threat, etc.

Disadvantage

Page 224: Ipu Java Notes

224

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Static page

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Static page Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Dynamic Pages

• Typically written in various scriptinglanguages or technologies such as ASP,PHP, Perl or JSP.

Advantages

üOffers highly personalized andcustomised visitor options.

üDatabase access improves thepersonalized experience (as opposed tousing just client side cookies)

Dynamic page

Page 225: Ipu Java Notes

225

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

üScripts can read in data sources anddisplay it differently depending on how itis run.

üCan create the illusion of being updatedregularly using time and date sensitiveroutines (or even randomizers) to displaypre-written text.

Dynamic page Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

Dynamic page Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 fileextension

• An HTML file can be created using a simple texteditor.

HTML Tag

Page 226: Ipu Java Notes

226

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

HTML Tag EXAMPLE

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

HTM or HTML Extension?

• When you save an HTML file, you can useeither the .htm or the .html extension. Wehave used .htm in our examples.

• With newer software we think it will beperfectly safe to use .html.

HTML Tag Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

HTML Tag Cont.

Page 227: Ipu Java Notes

227

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

HTML Tag Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

HTML Tag Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

HTML Tag Cont.

Page 228: Ipu Java Notes

228

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

HTML Tag Attributes

• HTML tags can have attributes. Attributesprovide additional information to an HTMLelement. Attributes always come inname/value pairs like this: name="value".

• Attributes are always specified in the start tagof an HTML element.

HTML Tag Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html><body><b>This text is bold</b><br><strong>This text is strong</strong><br><big>This text is big</big><br><small>

Formatted Text

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

This text is big

</small><br>

<em>

This text is emphasized

</em>

<br>

</html>

Formatted Text Cont.

Page 229: Ipu Java Notes

229

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Formatted Text Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<sub>subscript</sub><br>This text contains<sup>superscript</sup></body>

Formatted Text Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html><body>

<!--pre> !--comment--This ispreformatted text.It preserves both spacesand line breaks.</pre-->

Preformatted Text

Page 230: Ipu Java Notes

230

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<p>The pre tag is good for displaying computer code:</p>

<pre>for i = 1 to 20

print inext i</pre></body></html>

Preformatted Text

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html><body><address>Donald Duck<br>BOX 555<br>Disneyland<br>USA</address></body></html>

Preformatted Text

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Create hyperlinkThe 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:

Page 231: Ipu Java Notes

231

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<a href="url">Text to be displayed</a>

The <a> tag is used to create an anchor to linkfrom, the href attribute is used to address thedocument to link to, and the words betweenthe open and close of the anchor tag will bedisplayed as a hyperlink.

Create hyperlink

© Bharati Vidyapeeth’s 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 Vidyapeeth’s 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>

Page 232: Ipu Java Notes

232

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Attribute

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Font Color

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html><body bgcolor=#111111><pre><font color="#FFFFFF">This ispreformatted text.It preserves both spacesand line breaks.</FONT></pre>

Font Tag Cont.

Page 233: Ipu Java Notes

233

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<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 inext i</font></pre></body></html>

Font Tag Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Color Color code

Red #FF0000

Turquoise #00FFFF

Light Blue #0000FF

Dark Blue #0000A0

Light Purple #FF0080

Dark Purple § ¯/pre>Yellow #FFFF00

Pastel Green #00FF00

Pink #FF00FF

The following is an example of some of the COLOR codes(Hexadecimal Codes) that will be used with the COLORparameter in a <font> tag.

Font Tag Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Color Color code

White #FFFFFF

Light Grey #FFFFCC

Dark Grey § ¯hite Black § ¯lack Orange #FF8040

Brown § ¯rown Burgundy § ¯rown Forest Green § ¯rown Grass Green § ¯rown

Font Tag Cont.

Page 234: Ipu Java Notes

234

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 isthe content of a data cell.

• A data cell can contain text, images, lists,paragraphs, forms, horizontal rules, tables,etc.

Table

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html>

<caption>hello</caption>

<body>

<table>

<table border="1">

<tr>

<td>row 1, cell 1</td>

<td>row 1, cell 2</td>

</tr>

Table Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<tr>

<td>row 2, cell 1</td>

<td>row 2, cell 2</td>

</tr>

</table></body>

</html>

Table Example Cont.

Page 235: Ipu Java Notes

235

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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)

Table Attributes

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Table Attributes Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Table EXample Cont.

Page 236: Ipu Java Notes

236

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Table Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Frames

• With frames, you can display more than oneHTML document in the same browserwindow.

• Each HTML document is called a frame, andeach frame is independent of the others.

The disadvantages of using frames are:

• The web developer must keep track of moreHTML documents.

Frames

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Frameset Tag

• The <frameset> tag defines how to divide thewindow into frames.

• Each frameset defines a set of rows orcolumns.

• The values of the rows/columns indicate theamount of screen area each row/column willoccupy.

Frames Cont.

Page 237: Ipu Java Notes

237

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Frames Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<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%,*").

Frames Cont.

© Bharati Vidyapeeth’s 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>

Page 238: Ipu Java Notes

238

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html>

<frameset rows="25%,50%,25%">

<frame src="frame_a.htm">

<frame src="frame_b.htm">

<frame src="frame_c.htm">

</frameset>

</html>

Horizontal frameset

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

iframes are widely used to display web contentin a separate inline floating frame and theyare supported by all modern HTML browsers.

<IFRAME SRC="b.html" WIDTH=275 HEIGHT=200 ALIGN=RIGHT>

iframe

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

iframe Cont.

Page 239: Ipu Java Notes

239

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The IFRAME element allows you to insert aframe within a block of text. Inserting aninline frame within a section of text is muchlike inserting an object via the OBJECTelement: they both allow you to insert anHTML document in the middle of another,they may both be aligned with surroundingtext, etc.

• The information to be inserted inline isdesignated by the src attribute of thiselement. The contents of the IFRAMEelement, on the other hand, should only bedisplayed by user agents that do not support

iframe Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• frames or are configured not to display frames.• For user agents that support frames, the following

example will place an inline frame surrounded by aborder 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">therelated document.</A>]

• </IFRAME>

iframe Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

iframe Cont.

Page 240: Ipu Java Notes

240

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

iframe Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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. <!>

HTML Comment

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Lists: Lists are of two types1.Unordered list, and2.Ordered listUnordered Lists• An unordered list is a list of items. The list

items are marked with bullets (typically smallblack circles).

• An unordered list starts with the <ul> andend with </ul> tag.

• Each list item starts with the <li> and endwith </li> tag.

Lists

Page 241: Ipu Java Notes

241

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<ul>

<li>Coffee</li>

<li>Milk</li>

</ul>

• Coffee

• Milk

Unordered Lists

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.Coffee2.Milk

Ordered Lists

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Definition Lists

Page 242: Ipu Java Notes

242

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<dd>White cold drink</dd>

</dl>

Here is how it looks in a browser:

Coffee

Black hot drink

Milk

White cold drink

Definition Lists Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<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

Definition Lists Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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, radiobuttons, checkboxes, etc.) in a form.

• TextFields example given below:

Forms

Page 243: Ipu Java Notes

243

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Forms Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Password Fields<html><body><form action="">Username: <input type="text" name="user"><br>Password: <input type="password" name="password“ ></form>

Forms Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<p>

Note that when you type characters in apassword field, the browser displaysasterisks or bullets instead of the characters.

</p>

</body>

</html>

Forms Example Cont.

Page 244: Ipu Java Notes

244

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 valueof the src attribute is the URL of the image youwant to display on your page.

The syntax of defining an image:<img src="url">

Forms Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Forms Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<p>

Note that the syntax of inserting a moving image is no different from that of a non-moving image.</p>

</body>

</html>

Forms Example Cont.

Page 245: Ipu Java Notes

245

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html><body><p>An image from another folder:<img src="/images/netscape.gif"width="33" height="32"></p><p>An image from yahoo

Insert images from different locations

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<img src="http://www.yahoo.com/images/ie.gif">

</p>

</body>

</html>

Insert images from different locations

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Backgrounds• The <body> tag has two attributes where you

can specify backgrounds. The backgroundcan be a color or an image.

Bgcolor• The bgcolor attribute specifies a background-

color 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">

Background color

Page 246: Ipu Java Notes

246

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Background and text color

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Radio Button

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<input type="radio" name="sex" value="female"> Female

</form>

</html>

Note: Only one option can be chosen.

Radio Button Example

Page 247: Ipu Java Notes

247

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Checkbox Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Checkbox Example Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

The Form's Action Attribute and the SubmitButton

• 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 nameof the file to send the content to.

• The file defined in the action attribute usuallydoes something with the received input.

<html><form name="input" action=“filename.htm"

method="get/post">

The Form's Action Attribute and the Submit Button

Page 248: Ipu Java Notes

248

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

The Form's Action Attribute and the Submit Button

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Dropdown List

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Dropdown List Example

Page 249: Ipu Java Notes

249

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Textarea -Multi line input in a form<HTML><body><textarea name= address rows=“10” cols=“30”>bvicam , new delhi</textarea></body></html>Where name=namerows= number of visible text lines cols= number of visible width of text, in average character widths

Textarea Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html>

<body>

<form action="a.htm">

<input type="button" value="Hello world!">

</form>

</body>

</html>

This page will not go to next page.

Link Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Fieldset around dataThis example demonstrates how to draw a border with a caption around your data.

<html><body><fieldset><legend>Health information:</legend><form action="">

Fieldset

Page 250: Ipu Java Notes

250

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Fieldset Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<marquee behavior="alternate">This text willbounce from left to right</marquee>

Bgcolor: Sets the background color of themarquee.

<marquee bgcolor="blue">This marquee'sbackground color will be blue.</marquee>

Direction: Sets the direction of the marqueebox to either left-to-right or right-to-left. Laterbrowsers added support for a movie creditstyle bottom-up and top-down values.

marquee

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Marquee Cont.

Page 251: Ipu Java Notes

251

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Marquee Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Marquee Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Marquee Cont.

Page 252: Ipu Java Notes

252

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Marquee Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Static Web Sites

• For a static-content Web site, all contentappearing on Web pages is placed manuallyby professional Web developers.

• This is also called "design-time pageconstruction," because the pages are fullybuilt while the site is being developed.

• Static-content Web site is developed andthen maintained by experiencedprofessionals.

Static web sites

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• Such Web site usually costs less wheninitially developed, but then all futurechanges still have to be done by Webprofessionals. Therefore a static

• Web site can be more expensive to maintain,especially when you want to make frequentchanges to your site

Static web sites Cont.

Page 253: Ipu Java Notes

253

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Dynamic Web Sites

• On the other hand, pages in a dynamic-content Web site are constructed "on the fly"when a page is requested from a Webbrowser.

• Dynamic-content Web site, while stilldeveloped by professionals, can bemaintained directly by you, our customer.

• Such Web site initially costs more to develop,

Dynamic web sites

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• but then you don't have to pay Webprofessionals every time you need to changesomething on your site.

• If you plan to make frequent changes to yoursite, you most likely will be better off with adynamic Web site.

Dynamic web sites Cont.

© Bharati Vidyapeeth’s 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 technologiesused to create dynamic and interactive Websites.

• To most people DHTML means acombination of HTML, Style Sheets andJavaScript.

• DHTML is NOT a W3C Standard

• DHTML stands for Dynamic HTML.

Page 254: Ipu Java Notes

254

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• DHTML is not a standard defined by theWorld Wide Web Consortium (W3C). DHTMLis a "marketing term" - used by Netscape andMicrosoft to describe the new technologiesthe 4.x generation browsers would support.

• DHTML is a combination of technologiesused to create dynamic Web sites.

• To most people DHTML means acombination of HTML 4.0, Style Sheets andJavaScript.

DHTML Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• DHTML Technologies• With DHTML a Web developer can control

how to display and position HTML elementsin a browser window.

• HTML 4.0• With HTML 4.0 all formatting can be moved

out of the HTML document and into aseparate style sheet. Because HTML 4.0separates the presentation of the documentfrom its structure, we have total control ofpresentation layout without messing up thedocument content.

DHTML Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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 thestyle and layout of multiple Web pages all atonce. As a Web developer you can define astyle for each HTML element and apply it toas many Web pages as you want. To make aglobal change, simply change the style, andall elements in the Web are updatedautomatically.

DHTML Cont.

Page 255: Ipu Java Notes

255

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

ASP

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• PWS is a smaller - but fully functional - version ofIIS

• 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

ASP Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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"

ASP Cont.

Page 256: Ipu Java Notes

256

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

ASP Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

ASP Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

ASP Cont.

Page 257: Ipu Java Notes

257

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

ASP Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

ASP is used to add server-side scripts toyour web site, to make your web site moredynamic and interactive. You have learnedhow to dynamically edit, change or add anycontent of a web page, respond to datasubmitted from HTML forms, access anydata or databases and return the results to abrowser, customize a web page to make itmore useful for individual users.

Conclusion

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 .

Install IIS and run ASP

Page 258: Ipu Java Notes

258

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Install IIS and run ASP Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

Install IIS and run ASP Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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!

ASP Example

Page 259: Ipu Java Notes

259

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Add html tag to the text in ASP File

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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 methodis visible to everyone (it will be displayed in thebrowser's address bar) and has limits on theamount of information to send.

• If a user typed “Divya" and "Goel" in the formexample above, the URL sent to the server wouldlook like this:

http://localhost/firstform.asp?fname=Divya&lname=Goel

Requset.QueryString

© Bharati Vidyapeeth’s 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>

Page 260: Ipu Java Notes

260

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<%dim fname,lname1fname1=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>

A form with method="get"

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

A form with method="get" Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

A form with method=“get” Cont.

Page 261: Ipu Java Notes

261

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

A form with method=“get” Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<input type="submit" value="Submit" /></form>

• User input can be retrieved in two ways: With

Request.QueryString

or

Request.Form.

A form with method=“get” Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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

A form with method=“get” Cont.

Page 262: Ipu Java Notes

262

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Request.Form

• The Request.Form command is used tocollect values in a form with method="post".

• Information sent from a form with the POSTmethod is invisible to others and has no limitson the amount of information to send.

Request.Form

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<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 fnamefname=Request.Form("fname")If fname<>"" Then

Response.Write("Hello " & fname & "!<br />")Response.Write("How are you today?")

End If %></body></html>

Request.Form Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

A form with method post

Page 263: Ipu Java Notes

263

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<%dim fnamefname=Request.Form("fname")If fname<>"" Then

Response.Write("Hello " & fname & "!<br />")

Response.Write("How are you today?")End If%></body>

</html>

A form with method post Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

radio button<html><%

dim carscars=Request.Form("cars")

%><body>

<form action="demo_radiob.asp" method="post"><p>Please select your favorite car:</p>

<input type="radio" name="cars"

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

radio button example

Page 264: Ipu Java Notes

264

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

radio button example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

An Application

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

An Application Cont.

Page 265: Ipu Java Notes

265

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<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")%>>

An Application Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Banana<br /><input type="submit" value="Submit"></form><%if fruits<>"" then%>

<p>You like: <%Response.Write(fruits)%></p><%end if%></body></html>

An Application Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Another Application Cont.

Page 266: Ipu Java Notes

266

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Another Application Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Another Application Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

</body></html>

Another Application Cont.

Page 267: Ipu Java Notes

267

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• The ASP Server object is used to access the Server’s 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:

Server Object

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

• 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 doesn’t have a return value.

• executes an ASP page as a part of theparent (calling) ASP page.

Server Object Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Connection String

What is ADOdb?

• An object oriented library written in PHP thatabstracts database operations for portability.

• It is modelled on Microsoft's ADO, but hasmany improvements that make it unique (eg.pivot tables, generating HTML for pagingrecordsets with next and previous links,cached recordsets, HTML menu generation,etc).

Connection String

Page 268: Ipu Java Notes

268

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<% dim name,cre,total,conn,sqlname="Divya"cre="0123456"total="2000"dat="12-Mar-2008"set

conn=server.createobject("ADODB.connection")

conn.open "DSN=man"

Connection String Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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>

Connection String Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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

Another Connection String Example

Page 269: Ipu Java Notes

269

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<% set

conn=server.createobject("ADODB.connection")

conn.open "DSN=man"set rec=conn.execute("select * from shop")rec.movefirstwhile not rec.eof%>

Another Connection String Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<tr><td><%=rec.fields("dat")%>&nbsp;</td><td>

<%=rec.fields("cre")%>&nbsp;</td><td><%=rec.fields("name")%>&nbsp;</td><td><%=rec.fields("amount")%>&nbsp;</td></tr>

<%rec.movenextwend%></table></center></body></html>

Another Connection String Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

JavaScript is a scripting language that enables webdevelopers/designers to build more functional andinteractive websites.

• Allows you to write code to control all HTMLelements.

• CSS is used to style HTML elements.

Common uses of JavaScript include:• Alert messages• Popup windows• Dynamic dropdown menus• Form validation• Displaying date/time

JavaScript

Page 270: Ipu Java Notes

270

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

JavaScript usually runs on the client-side (thebrowser's side), as opposed to server-side(on the web server). One benefit of doing thisis performance. On the client side, JavaScriptis loaded into the browser and can run assoon as it is called. Without running on theclient side, the page would need to refresheach time you needed a script to run.

JavaScript Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

<html><body><script type="text/javascript">document.write("This is my first JavaScript!");</script></body>

</html>

JavaScript Example

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Event Handler

Event that it handles

onBlur User has left the focus of the object. For example, they clicked away from a text field that was previously selected.

onChange User has changed the object, then attempts to leave that field (i.e. clicks elsewhere).

onClick User clicked on the object.

onDblClick User clicked twice on the object.

onFocus User brought the focus to the object (i.e. clicked on it/tabbed to it)

onKeydown A key was pressed over an element.

onKeyup A key was released over an element.

onKeypress A key was pressed over an element then released.

JavaScript Event

Page 271: Ipu Java Notes

271

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

onLoad The object has loaded.

onMousedown

The cursor moved over the object and mouse/pointing device was pressed down.

onMouseup

The mouse/pointing device was released after being pressed down.

onMouseover

The cursor moved over the object (i.e. user hovers the mouse over the object).

onMousemove

The cursor moved while hovering over an object.

onMouseout

The cursor moved off the object

onReset User has reset a form.

JavaScript Event Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

onSelect User selected some or all of the contents of the object. For example, the user selected some text within a text field.

onSubmit User submitted a form.

onUnload User left the window (i.e. user closes the browser window).

onLoad The object has loaded.

onMousedon

The cursor moved over the object and mouse/pointing device was pressed down.

onMouseup The mouse/pointing device was released after being pressed down.

onMouseover

The cursor moved over the object (i.e. user hovers the mouse over the object).

JavaScript Event Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

onMousemove

The cursor moved while hovering over an object.

onMouseout

The cursor moved off the object

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.

onSubmit User submitted a form.

onUnload User left the window (i.e. user closes the browser window).

JavaScript Event Cont.

Page 272: Ipu Java Notes

272

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Basic knowledge of HTML and graphicdesign work will go a long way in yourdesigning a website. Database templatesalso facilitate you to make changes to yoursite much more easily, and help you changecertain elements without recreating the entirepage from scratch the dividends of simplicitycan not be ignored and put at stake Whiledesigning a website it is important that thesite is attractive, fast-loading, user friendly,focuses on your content and has a highstickiness factor to it.

Conclusion

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

A Web page is really just a text document indisguise and HTML tags, CSS, ASP,JavaScript, etc are used. You can cleanlyorganize content using headings andparagraphs. Lists can help break up contentinto more web-friendly chunks .Tables aregrids with headings, rows and cells.Hypelinks and Animation are used to make awebsite more interactive.

Summary

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Objective type questions

Q1)We send and receive HTML file using which protocol?

a. SMTPb. 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>

Review Questions

Page 273: Ipu Java Notes

273

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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=70ac9566533a2665b6597346aab7f985 ></a>

c. <a connect=\"page.htm\" ></a>

d. <a attach=\"page.htm\" ></a>

Q4) Java is different from JavaScipta) True

b) FalseQ5)JavaScript is a server side scripting.

a) True

b) False

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Short QuestionsQ1)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?

Review Questions Cont.

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

Long QuestionsQ1)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?

Review Questions Cont.

Page 274: Ipu Java Notes

274

© Bharati Vidyapeeth’s Institute of Computer Applications and Management, Divya Goel, New Delhi-63. ‹#›

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.

References