Table Of Content1
JSP JAVA BASICS
INTRODUCTION TO JAVASERVER PAGES
FEATURES OF JAVASERVER PAGES
J avaServer Pages (JSP) is technology developed by
Sun Microsystems that is used to create powerful
and dynamic Web sites. Create Dynamic Web Sites Work With Databases
Dynamic Web sites contain Web pages that An important feature of JavaServer Pages is the
display constantly changing content. Using ability to connect to a database. JSP pages can
JavaServer Pages, you can determine the content be used to make information stored in a database
a Web page displays, depending on many available to the users who visit a Web site. Using
Web Servers Servlet Technology
different factors. For example, you can have a databases to store information and JSP pages to
You do not require a dedicated Web server to JavaServer Pages is based on servlet technology, page automatically present different content to access the information is an efficient method of
publish the JSP pages you create. You can simply which allows Web developers to use Java code users depending on the current date or the user's displaying up-to-date information in a Web site.
install Web server software on your own computer. to create dynamic Web pages. JavaServer Pages location. Dynamic Web pages are more useful
JavaServer Pages can also allow users to manipulate
A popular example of Web server software that simplifies the process of creating dynamic pages to each individual user than static Web pages.
the data in a database. For example, a JSP page can
includes support for JavaServer Pages is Tomcat. using Java.
be used to add, delete or edit records in a database.
The Tomcat Web server is commonly used by Web
developers who create JSP pages. Create Interactive Web Sites
Server-side Processing
You do not require any special development tools Interactive Web sites contain Web pages that Using JavaBeans
JavaServer Pages uses a JSP engine that is part of exchange information between the Web site
to create and view JSP pages. All you need is a text JavaBeans are re-usable components that allow
the Web server, so the processing of JSP code takes and the user. JavaServer Pages allows Web
editor and a Web browser. Web developers to keep the Java code for a JSP
place on the server. When a user requests a JSP developers to easily create Web pages that
page separate from the HTML code for the page.
page, the JSP engine processes the page and then process information from a user and then
This helps prevent the code on a JSP page from
Versions sends the result as HTML code to the user's Web generate content depending on the information
becoming long and difficult to work with and
browser. This allows JSP pages to be viewed by submitted by the user. Interactive Web sites
JavaServer Pages 1.1 is the current version of allows Web developers to share and re-use Java
every Web browser. allow Web developers to tailor the content
JavaServer Pages, although the specification for a code. JavaBeans also enable specialization when
of Web pages to better appeal to the user.
newer version 1.2 has been proposed. On average, developing a Web site by allowing experts in Web
a new version of JavaServer Pages is produced each JSP Implicit Objects page design to work with the HTML content for
year. Each new version offers more features than Increased Security a page while programmers develop the Java code
previous versions of the technology. The Web JSP includes implicit objects that can be used to for the page.
perform specific tasks. For example, the session Because JavaServer Pages code is processed on
server you are running will determine the version
object can be used to store session information the Web server, the user cannot access the code
of JavaServer Pages you can use and the tasks you
can perform. about a client computer as the client navigates used to create a JSP page. This makes it safer to Using Custom Tags
a Web site. Other commonly used implicit work with sensitive data, such as login names
JavaServer Pages technology allows Web developers
objects include the responseobject, which sends and passwords. If a user views the source code
to create their own custom tags that perform
Programming Languages information to a client, and the requestobject, of a JSP page within a Web browser, all the user
specific tasks. Like JavaBeans, tag libraries are
which retrieves and controls information sent will see is the HTML code that was generated
The Java programming language forms the basis re-usable components that help keep the Java
from a client to the Web server. by the Web server to create the page, not the
of JavaServer Pages technology. The version of code for a JSP page separate from the HTML code
JavaServer Pages code itself.
Java you use depends on the Web server you for the page. Once a tag library containing the
are running and the version of JavaServer Pages code for a custom tag has been created, the
technology you are using. custom tag can be used in JSP pages.
2 3
1
JSP JAVA BASICS
PROGRAMS FOR CREATING JAVA CODE
The first step in creating Java programs is to select the
INTRODUCTION TO JAVA
method you want to use to create the Java programming
code, or source code.
J ava is a programming language used to create You can also utilize your knowledge of Java to work Text Editors Notepad
applications for the World Wide Web. Java was with other Java-based technologies, such as JavaBeans.
originally developed by Sun Microsystems in Since all Java source code is plain text, you can Microsoft Notepad is a simple text editor available
1991 for use in consumer electronics such as handheld The popularity of JavaServer Pages is partly due to the use a simple text editor to create the source code. on all computers running the Windows operating
computers and television sets, but the language was fact that people who are already familiar with the Java system. Most operating systems contain a text
later modified for use on the Web. Java is now a programming language do not need to learn a new editor similar to Notepad. While very basic,
full-featured programming language that is easy to programming language in order to use JavaServer Pages. For Non-Windows Operating Systems Notepad is more than adequate for creating
use and understand. Since JavaServer Pages uses Java code to create Web There are many text editors that can be used to create source code and is widely used by programmers.
pages, programmers can use their existing knowledge Java source code on UNIX computers. Most UNIX
Java is the main programming language used in of Java to create JSP pages. JavaServer Pages also uses computers have multiple text editors installed by default. UltraEdit
JavaServer Pages. While in-depth knowledge of Java is programming code that is unique to JavaServer Pages Text-based editors such as vi and Emacs are very popular
not required, in order to effectively use JavaServer Pages and is not strictly Java code. and can be configured to suit your needs. If your UNIX UltraEdit is a sophisticated text editor popular
you need to understand the basics of the language. A system has a graphical interface, like GNOME, then with many programmers. UltraEdit’s advanced
thorough understanding of Java will enable you to create you should already have access to graphical text editors, features include syntax highlighting, which
more sophisticated, versatile and efficient JSP pages. such as gnotepad+. highlights the Java code to make the code easier
to read, and the ability to save Web pages directly
On the Macintosh operating system, you can use the to a Web server. UltraEdit is a shareware program
SimpleText text editor included with the system. available at www.ultraedit.com.
Features Object-Oriented
Java includes a number of features that make the Java is an object-oriented programming language,
HTML Editors HomeSite
language ideal for use on the Web. Java programs so if you understand the fundamentals of how
transfer quickly over the Web since the language Java works, you will understand the fundamental HTML editors are programs specifically designed to Allaire's HomeSite is a comprehensive HTML
was created to be portable and file sizes are small. concepts of object-oriented programming. help you create Web pages. Compared to text editors, editor designed for creating Web pages on the
In addition, Java is platform independent. This means Object-oriented programming is a type of HTML editors usually offer more advanced features Windows operating system. HomeSite is suitable
that a Java program can be run on any computer that programming that treats separate pieces of code to help you work with HTML and Java code. for beginners creating a small number of Web
has a Java virtual machine, regardless of the operating as distinct modules, or objects. It is often easier pages and for experienced Web masters producing
system the computer uses. This feature is invaluable to learn object-oriented programming if you do complicated Web pages and Web sites. HomeSite
BBEdit
for use on the Web, where computers using various not have vast experience with programming includes syntax coloring for JavaServer Pages code
languages and environments must interact. languages that are non-object-oriented. Despite BBEdit is a sophisticated HTML editor for the and allows you to view the results generated by
its apparent initial complexity, object-oriented Macintosh operating system. BBEdit makes it the code within HomeSite. HomeSite is available
programming is easy to learn. easy to create JavaServer pages and is available at www.allaire.com.
at www.barebones.com.
Bytecode
When a Java program is compiled, the program is not
Security
immediately translated into machine code, which are Integrated Development Environments JBuilder
instructions specific to a particular operating system. Java provides a number of advanced security Instead of a text editor, you can use a Java Integrated Borland’s JBuilder is one of the more popular
Instead, it is compiled into an intermediate language, features, such as access controls, which are not Development Environment (IDE). An IDE is a program Java IDEs. JBuilder is a sophisticated, full-featured
called bytecode, that can be interpreted by a Java offered by many other programming languages. that allows you to create, execute, test and organize your IDE that can be used to create JSP pages and
virtual machine. When the Java program is run on a Java programs may contain viruses or code that source code. IDEs often contain additional features such complex Java applications. JBuilder is also available
computer that has the Java virtual machine, the Java can cause computer problems. Java’s access as sample code, reusable components and troubleshooting for various UNIX operating systems. JBuilder is
interpreter translates the bytecode into code that the controls allow programmers to use untrusted capabilities. IDEs are commonly used to create larger available at www.borland.com/jbuilder.
computer running the program can understand. Java code in their programs without putting applications and to enable multiple programmers to work
their systems at risk.
on a single project at the same time.
4 5
1
JSP JAVA BASICS
OBJECT-ORIENTED PROGRAMMING CONCEPTS
J ava shares many concepts with other object-oriented The amount of object-oriented programming a Web site
programming languages, such as C++ and Perl. While requires depends on the size and scope of the Web site.
Methods Arguments
object-oriented programming languages use the same It also depends on where you store the Java code. Storing
concepts, the terminology and coding systems sometimes the Java code in the JSP pages themselves requires much Methods are code that objects use to perform One or more values, called arguments, may be passed
differ. For example, in Perl, a single value in an object is less object-oriented programming than storing the Java a specific task. A class used to create objects to a method to provide the method with input data or
referred to as a property. In Java, this is referred to as a field. code in external modules, referred to as JavaBeans. can contain multiple methods. The methods additional information about how to perform a task.
in a class usually perform related tasks. For example, when using a method that creates tables
For example, in a class used to format text on a Web page, you may need to pass the number of
information on Web pages, one method may rows and columns for a table to the method. Some
be used to generate the code needed to format methods do not require any arguments.
JAVA CONCEPTS
the headers of paragraphs. Another method
may be used to format information in a table.
The behavior of methods may be influenced Return Values
Classes Objects
by the values stored in the fields of the object. A method may return a value after performing a
A class is the Java code that serves as a template or An object is a package of code that is
specific task. The return value may indicate the result
plan for creating objects, which are the core features composed of data and procedures that make
of a calculation or it could indicate whether or not
of object-oriented programming. A single class can use of the data. Objects have two primary
the task was performed successfully. For example,
be used to create many objects. For example, a class functions–to store information and to perform
a method that writes information may return a
containing code for generating messages can be tasks. Objects contain fields, which are used
true or false value, which the program can use to
used to create an object that displays a welcome to store information, and methods, which are
determine the next code that should be executed.
message at the top of each Web page. The same used to perform tasks. Objects can be created
class can be used to create another object that to perform a single task or a range of related
displays copyright information at the bottom of a tasks. Multiple objects can be created using the
page. Classes can be used and shared by more than same class. When an object is created, it is said
one Java program and therefore help programmers to be an instance of the class used to create the Object Relationships Data Hiding
avoid having to constantly rewrite the same type of object. The following diagram shows how a single class can be Data hiding makes classes easier to use
code. used to create multiple objects, each with its own distinct by hiding the fields and methods of the
fields and methods. classes from other parts of the program.
The program then has to know only
CLASS how to access the class, not the internal
Car workings of the class. Data hiding is
often used in programs to protect classes
Fields Create Instance Create Instance from tampering and to ensure that the
Fields, also known as data fields, are the properties or changes. With a field value of 1, the message will be methods of the classes are used as
attributes associated with an object. In comparison to updated once every minute. When the field value is OBJECTS originally intended. A programmer can
other programming languages, fields can be thought changed to 60, the message will be updated once an myCar yourCar modify and maintain the code within the
of as variables of the class. Fields can store different hour. class without affecting the programs that
types of data, such as strings of text, integers and FIELDS FIELDS use the class. This also helps ensure that
references to other objects. When multiple objects are created using the same Color: Blue Color: Red objects developed by multiple people are
class, it is typical for the objects to be the same except Speed: 60 mph Speed: 80 mph compatible.
Changing the value of an object's fields usually affects for the values held in the objects' fields.
the behavior of the object. For example, in an object METHODS METHODS
used to display a changing message on a Web page,
Start Engine Start Engine
a field may be used to specify how often the message
Accelerate Accelerate
6 7
1
JSP JAVA BASICS
THE JAVA CLASS LIBRARY
Commonly Used Java Class Library Packages
T
he Java class library is a collection of predefined
classes that you can use in your programs. The Java The Java class library contains more than 70 packages.
class library is also known as the standard class library The following is a list of some of the most commonly
or the Java Applications Programming Interface (Java API). used packages in the library.
java.io java.sql
Classes Java Class Library Installation
Contains classes that allow Java programs Contains classes that allow Java programs
Some predefined classes are used often in Java The Java class library is installed automatically to perform data input and output tasks. to access and process data from a database.
programs, such as those used to display output, when the Java Software Development Kit is
while other classes are used infrequently, such installed on a computer. The Java class library is
as the classes used to create Graphical User stored in a Java archive file named rt.jar in the lib
java.lang java.text
Interfaces (GUIs). The classes included in the Java subdirectory of the jre directory. The jre directory
class library are available to every Java program is located in the main Java SDK directory. You do Contains the fundamental classes of the Java Contains classes that allow a Java program
you create. Using the predefined classes in the not need to adjust any settings on your computer programming language and is automatically to manipulate strings, dates, numbers and
Java class library saves you time and effort when to specify the location of the Java class library loaded by the Java compiler. characters.
creating programs. before using a class from the library in your code.
java.math java.util
Contains classes that allow Java programs Contains utility classes that allow Java programs
to perform arbitrary-precision arithmetic. to perform various tasks such as date and time
operations and random number generation.
Packages Import Packages
The classes that make up the Java class library You can import a package from the Java class library java.lang.ref
are organized into packages. A package is a set into a Java program. This allows you to efficiently java.util.jar
of related classes stored in a separate directory. use all the classes in the package. The java.lang Contains classes that allow Java programs
For example, classes that are used to generate package is automatically imported into every Java to interact with the garbage collector, which Contains utility classes that allow Java programs
output are stored in a different package than program you create. For more information about performs memory management tasks. to read and write Java ARchive (JAR) files.
classes used to process data from a database. importing a package, see page 52.
Generally, classes stored in the same package
can easily access each other. java.lang.reflect java.util.zip
Package names are based on the directory Contains classes that allow Java programs Contains utility classes that allow Java programs
Create Packages
structure that stores the classes in the package. to obtain information about the variables to read and write ZIP files.
For example, the classes in the java.util In addition to using predefined classes from Java class and methods of loaded classes.
package are stored in the util subdirectory library packages, you can author your own classes and
of the java directory. store them in packages you create. For example, if you javax.swing
create three classes to work with a Web site, you could
java.security
store these classes in a package named website. You Contains classes for creating Swing Graphical
could then use the classes from the package when Contains classes that allow Java programs User Interface (GUI) components. Swing GUI
creating other Java applications. For more information to carry out security procedures, such as components can be used on all platforms.
about creating packages, see page 50. controlling access and encrypting data.
8 9
1
JSP JAVA BASICS
JAVA CONVENTIONS
T o use the Java programming language effectively, there
are several conventions you should know. For more
information about the conventions used in Java, you
can consult the Java SDK documentation.
White Space Comments
White space is the term used to describe You can include comments in your Java code
characters that are not displayed or printed, to explain important or difficult sections of
Semicolons
such as spaces, tabs and newlines. Using white code. Adding comments to your code is a good
Most Java statements end with a semicolon (;). Java where one is not needed. When an error occurs due to space in your Java code can greatly improve programming practice and can help make the code
statements that include a block of code, known as the the omission or misplacement of a semicolon, the Java the readability of your code. For example, easier to understand. Comments are particularly
body of the statement, are the exception. Examples of compiler may indicate that the error is in the statement x + 1 / age is easier to read than x+1/age. useful if you or someone else will need to modify
these types of statements include methods, conditional following the actual location of the error. To avoid these The Java compiler ignores white space. This or troubleshoot the code in the future. For more
statements and statements that create a loop. The Java types or errors, you should always review your Java means that using white space will not affect information about adding comments to your Java
compiler will stop compiling code and report an error if code carefully before compiling the code. the speed at which your Java code is compiled. code, see page 15. Using descriptive names for
a required semicolon is missing or a semicolon is used items such as classes, methods and variables can
also make your code easier to understand.
Braces Indenting
Java statements that include a body use braces {}to When working with a Java statement that includes a Keywords
indicate the beginning and the end of the body. A body body, you should always indent the code in the body.
The Java programming language includes many keyword inappropriately, the Java compiler will
often contains several statements. If a statement block Indenting makes your code easier to read. Tabs or
keywords. A keyword is a word reserved for use usually detect the error and stop compiling the
contains only one statement, braces are typically not spaces can be used to indent code. To keep your
only by Java. You cannot use keywords as variable code. The following table displays a listing of
required. There are two accepted formats that you can Java programs consistent, you should use the same
names or values in your code. If you use a Java Java keywords:
use when including braces in your Java code. You should indenting style in all your code.
choose one format and then use that format consistently
throughout your code. abstract else interface super
Code without indents:
The most widely used format places the opening brace public static void main(String[] args) boolean extends long switch
on the same line as the Java statement. The closing brace {
int counter = 1; break false native synchronized
is placed on its own line and in the same column as the
while (counter <= 5)
first character of the Java statement that uses the braces. { byte final new this
System.out.println(counter);
Example: counter++; case finally null throw
public static void main(String[] args) { }
System.out.println("Hello."); } catch float package throws
System.out.println("My name is Bob.");
}
char for private transient
Code with indents:
public static void main(String[] args) class goto protected true
The second format places each brace on its own line.
{
The braces are in the same column as the first character int counter = 1; const if public try
of the Java statement that uses the braces. This format while (counter <= 5)
is easier to read, but adds more lines to your Java code. { continue implements return void
System.out.println(counter);
Example: counter++; default import short volatile
public static void main(String[] args) }
{ } do instanceof static while
System.out.println("Hello.");
System.out.println("My name is Mary."); double int strictfp
}
10 11
1
JSP JAVA BASICS
INSTALL THE JAVA SOFTWARE
DEVELOPMENT KIT
The Java SDK installation program is over The Java SDK documentation can be
20 megabytes (MB) in size. If you are downloaded separately from the Java Web site.
T
he Java Software Development Kit (SDK) is a installation program selects a folder where the kit will using a modem to connect to the Internet, It is recommended that you install and review
collection of programs used to compile and execute be installed for you. It is recommended that you accept the program can take a few hours to the Java SDK documentation, particularly if you
Java programs. You need to install the Java SDK in this folder. During the installation, you can select which download. For convenience, you may want will be creating your own Java applications.
order to install the Tomcat Web server, which allows you components of the Java SDK you want to install, such as to start the download and let it continue
to create and test JavaServer Pages. demos. It is recommended that you install all the available through the night.
components. After installing the Java Software Development Kit,
The Java Software Development Kit is constantly being
you may want to add the location of the Java SDK
updated. A recent release of the Java SDK for Windows is The installation program allows you to choose to view a
programs to the path variable of your computer's
included on the CD-ROM disc that accompanies this book, README file that contains information about the release If you already have a previous release of
operating system. Setting the path variable will
but you should make sure you use the latest release of the of the Java Software Development Kit you installed and the Java SDK installed on your computer,
allow you to run your Java programs from any
kit. More information about the latest release of the Java any last minute changes to the documentation. If you it is recommended that you uninstall the
folder on the computer without having to type the
SDK is available on the Java Web site at java.sun.com. choose to display the file, it will open when the installation previous release before upgrading to the
full path to the Java compiler and interpreter. Refer
The Java SDK is also currently available for the Sun Solaris is complete. You should carefully review the README file latest release of the Java SDK.
to the documentation that came with the Java SDK
and Red Hat Linux platforms. Downloading and installation for any new release of the Java SDK you install.
and your operating system documentation for
instructions are available at the Java Web site.
Once the Java SDK has been installed, you should restart information about changing the path variable.
On the Windows platform, the Java SDK is installed using your computer, particularly if you are upgrading from an
a standard Windows installation program. The Java SDK older release of the Java SDK.
INSTALL THE JAVA SOFTWARE DEVELOPMENT KIT
Program Files 27514 K
⁄Double-click the icon for the (cid:2)This area displays (cid:2)This area displays the ‹Click Yes to accept the (cid:2)This area displays the ›Click Next to (cid:2)Each component in this area (cid:2)A dialog box appears
Java SDK installation program information about the license agreement you agreement and continue. folder where the Java SDK continue. that displays a check mark ( ) when the installation is
to start installing the kit. Java SDK installation must read and accept will be installed. will be installed. You can click the complete. Click Finish
(cid:2) program. before continuing. (cid:2) box beside a component you do not to close the dialog box
A setup window appears You can click Browse
want to install ( changes to ). and then restart your
on the screen and a welcome ¤Click Next to to install the Java SDK in
computer.
dialog box is displayed. continue. a different folder. ˇClick Next to install the Java SDK
components on your computer.
12 13
1
JSP JAVA BASICS
Class names can begin with any letter, an You should always include comments to
DECLARE A CLASS underscore (_) or the symbol $, £or Y__. Class make your Java code easier to understand.
names cannot begin with a number or contain Comments are helpful if you or other people
any punctuation, such as a period or a comma. need to modify or troubleshoot the code.
A fter installing the Java Software Development Kit, methods, which are structures that contain the Java code Class names also cannot be the same as any of Any code you write should include comments
you can begin creating Java programs. When creating for specific actions. For more information about declaring the Java reserved words, such as do, whileor that indicate the author's name and the main
Java programs, the first step is to declare a class. A a method, see page 16. public. These naming rules also apply to the purpose of the program. Comments are
class is the smallest unit of Java code that can be run and naming of methods, fields and parameters in preceded by // and can be included at the
The class name you choose must be the same as the
is the fundamental structure that Java applications use to Java code. end of a line of code or on a separate line.
filename with which the program is saved. For example,
group together related code. For example, a class called
CheckText may contain all the code required to analyze and if the class in your Java program is called DisplayText, the Example:
program must be saved with the filename DisplayText.java. // Author: Martine Edwards
validate a string of text. The CheckText class can be used You may want to add comments that span
It is also important to note that Java is a case-sensitive class DisplayWelcome // A welcome message
on its own in a program or used in conjunction with other language. If the program is saved with the filename multiple lines to your Java code. To do so, {
classes. All Java applications must include at least one class. type /*before the first line of the comment // The body of the class
displaytext.java, an error may occur when you attempt
and */after the last line of the comment. }
Java classes are declared using the keyword class to compile the program.
followed by the class name. The class name should be easy Example:
to understand and should indicate the purpose of the class. /*
The class name is followed by a pair of braces {}. All This Java application
displays a welcome message when
methods and Java code in the class must be placed
the program is executed
between the braces. The code between the braces is */
referred to as the body of the class and is made up of
DECLARE A CLASS
⁄Start the text editor ¤Type class. ‹Type the name of the ›Type an opening brace ˇPress Enter to create ÁType a closing brace Note: To declare methods for
you will use to create a class you want to create. to mark the beginning of blank lines where you to mark the end of the the class you created, see
Java program. the body of the class. will type the body of the body of the class. page 16.
class.
14 15
1
JSP JAVA BASICS
DECLARE A METHOD
The name of the method should indicate the A method can generate a result which is
purpose of the method. A method name can returned to the code. The return type for
O nce a class has been declared, methods can be A method declaration should also include a return type. consist of multiple words. To make the name a method that returns a value can be any
easier to read, you can capitalize the first valid data type in Java, such as String,
declared for the class. Methods are similar to A return type specifies the type of value the method returns.
letter of each word, such as DisplayMyName. byteor boolean. The body of a method
subroutines and functions that are found in other, If a method does not return a value to the code, the return
non-object-oriented programming languages. Methods type should be void. For more information about return that returns a value must also include a
returnstatement. An error may occur if
contain lines of code that perform a specific task, such values in methods, see page 38. You can use different access modifiers when
the data type of the value that is returned
as displaying an invoice or calculating the final total of declaring a method, depending on how the
The name of a method is followed by parentheses, such as does not match the return type specified
an invoice. method will be accessed. The publicaccess
DisplayInvoice(). in the method declaration.
modifier indicates that the method can be
Using methods makes it easy to re-use sections of code
Every Java application must have a method called main, accessed by any class and subclass within any
and allows you to group lines of code into smaller, more
manageable sections. This makes it easier for people to in which all the other methods required to run the program package. The protectedaccess modifier Every mainmethod must include the
understand and troubleshoot the code. are called. The argument String[]argsmust be placed indicates the method can be accessed by any public, staticand voidmethod
within the parentheses at the end of the method name for class within the same package and any subclass modifiers. If one or more of the method
You can use method modifiers, such as publicand a mainmethod. This argument indicates that the method of the class that contains the method within a modifiers are entered in a different order,
static, to tell Java how a method is to be used. The can accept strings passed from the command line when different package. The privateaccess modifier the code may generate an error message.
publicmethod modifier is an access modifier that the Java program is executed. indicates the method can be accessed only by
indicates that this method can be used by other classes the class that contains the method.
The method declaration ends with a pair of braces. The
that you create. A staticmethod modifier indicates that
code that makes up the body of the method is placed
the method can be used by any program without having
inside the braces.
to create an object of the class that declares the method.
DECLARE A METHOD
⁄In the body of a class, Note: A mainmethod must ¤Type the return type ‹Type the name of the ›Between the parentheses, Note: The arguments of a ˇType the opening and (cid:2)To create the body
type the method modifiers include the publicand of the method. method followed by (). type any arguments the mainmethod must be closing braces that will of the method, see
for the method you want staticmethod modifiers. method requires. String[]args. contain the body of the page 18.
Note: A method that does not
to declare. method.
return a value must include the
voidreturn type.
16 17
1
JSP JAVA BASICS
To start a new line at the end of a line of text, you can
use the escape sequence \n. Using the escape sequence
\nallows you to display text over multiple lines.
CREATE THE METHOD BODY
TYPE THIS: RESULT:
class MyIntroduction
T he body of a method contains the Java code that is Methods can be used to display information on a user's { My name is Martine Edwards.
used to perform a task and must be created within screen. To display information, System.out.print public static void main(String[] args) This is my first Java Program.
{
the method's braces {}. can be used. The Systemobject is included in the Java
System.out.print("My name is Martine Edwards." + "\n");
SDK and is created automatically when a Java program
The code in the body of a method is often used to call, or System.out.print("This is my first Java Program." + "\n");
is executed. The outfield is used to send information }
access, another method. The called method can be declared to the standard output device, typically the screen. }
in the same class or in a different class. Re-using methods
The printmember takes an argument that must be
saves you time and effort when writing Java programs. For
enclosed in parentheses. System.out.printcan
example, if you create a method that displays your name
be used to display any type of data used in Java. When
and e-mail address, the same method can be used in any The classes and methods included with the Java System.out.printlncan also be used
using System.out.printto display a string of text,
Java application you create. Software Development Kit are collectively known to start a new line.
the string must be enclosed in quotation marks.
as the Java class library, also called the Java
The Java Software Development Kit includes many classes Once you have finished creating the code for your Java Application Programming Interface or Java API. ESyxsatmepm.leo:ut.println("The Java program has been executed.");
and methods that can be used to perform a wide variety program, save the code as a text file with the .java The Java SDK documentation describes all the System.out.println("Have a good day.");
of common tasks. For example, the Java SDK includes a extension. The name of the file must be exactly the classes and methods available in the Java class
class called math. The mathclass contains several methods same as the name of the first class defined in the code. library. If you have not already installed the
that perform mathematical calculations. For example, to Java SDK documentation, you can obtain the
determine the square root of a number, you can simply documentation on the Web at java.sun.com.
call the sqrtmethod from the mathclass.
CREATE THE METHOD BODY
History
Desktop
My Documents
My Computer
My Network Pl...
⁄Enter the code that ¤In the body of the method, (cid:2)In this example, ‹Type any arguments (cid:2)String arguments must SAVE JAVACODE (cid:2)You may need to place
declares the class and the type the code for the task you System.out.print the code requires. be enclosed in quotation ⁄Save the Java code as a text file. quotation marks around
method you want to use. want to perform. is used to display marks. the name of the file.
output. (cid:2)The name of the file must be (cid:2)
You are now ready to
exactly the same as the name of
compile the Java code.
the first class in the code. The
See page 20 to compile
filename must also have the .java
Java code.
18 extension. 19
1
JSP JAVA BASICS
COMPILE JAVA CODE
C ompiling Java code converts the source code into c:\jdk1.3\bin\javac. For information about setting the path When compiling Java source code, there are
bytecode. Bytecode contains instructions that the variable, refer to the Java SDK installation instructions or two main types of errors that can occur.
Java interpreterexecutes. your operating system's documentation.
Java SDK Errors Source Code Errors
A Java compiler is required to compile Java code. The Java Before compiling Java code, the Java compiler checks the
Software Development Kit includes a Java compiler called code for errors. If an error is found, the code will not be If your operating system cannot locate the Java A wide variety of errors can occur in Java source
javac. The javac compiler can only be executed from the compiled and an error message will be displayed. compiler, a problem may have occurred when code. When the Java compiler finds an error in source
command prompt. If you are using a Windows operating the Java SDK was installed. Java SDK errors code, the compiler displays an error message that
If the Java code is successfully compiled, the resulting
system, you will need to open an MS-DOS Prompt or usually result in an error message such as "bad usually specifies the error type and where the error
bytecode will be saved in a new file with the .class
Command Prompt window to use javac. command or file name." To correct this type of was detected. For example, the error "Program.java:5:
extension. The name of the new file is taken from the
error, first determine the correct path to the invalid method declaration" indicates that an error
To compile Java source code, you enter the name of the name of the file that stores the Java source code. For
compiler. If you cannot locate the Java compiler, involving a method declaration was generated at line
Java compiler, such as javac, at the command prompt, example, when the code in a file named Program.java
try re-installing the Java SDK. If you were able 5 in the Program.java file. It is important to note that
followed by the name of the file that stores the code is compiled, the bytecode is saved in a file called
to confirm the path to the compiler, ensure that the line number indicates the line that the compiler
you want to compile. The filename must have the .java Program.class. The filenames of Java programs are
you have not made any typing mistakes in the was processing when the error was detected, which
extension. Depending on whether you have added the case sensitive on most platforms.
path. is not necessarily the line that contains the error.
location of the Java SDK programs to your operating
Once Java source code has been compiled, the Java
system's path variable, you may need to specify the
program is ready to be executed.
full path to the Java compiler, which is typically
COMPILE JAVA CODE
C:\WINDOWS>cd\java C:\WINDOWS>cd\java C:\WINDOWS>cd\java C:\WINDOWS>cd\java
C:\java>javac C:\java>javac Displaywelcome.java C:\java>javac Displaywelcome.java
C:\java>
⁄Open the window that ¤Move to the directory ‹To compile the Java (cid:2)If you have not added ›Type the name of the file ˇPress Enter to compile (cid:2)If the Java code was Note: If an error message
allows you to work at the that stores the Java code code using the javac the location of the javac that stores the Java code you the Java code. successfully compiled, the appears, the Java code was
command prompt. you want to compile. compiler, type javac. compiler to your operating want to compile, including command prompt re-appears. not successfully compiled.
system's path variable, you the .java extension. (cid:2)
The Java program is now
will need to type the full
ready to be executed. See
path to the javac program.
page 22 to execute a Java
20 program. 21