0% found this document useful (0 votes)
72 views35 pages

Unit 2. Introduction To Java

The document provides an overview of Java and its history: [1] Java originated in 1990 as a language called Oak that was designed for personal digital assistants. It was later renamed Java and released for web development. [2] Java allows programs to be written once and run on any platform, addressing issues with other languages. It also includes tools for building graphical user interfaces. [3] Java programs can be applications, which run independently, or applets, which are executed within a web browser. The document provides a simple example of each.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views35 pages

Unit 2. Introduction To Java

The document provides an overview of Java and its history: [1] Java originated in 1990 as a language called Oak that was designed for personal digital assistants. It was later renamed Java and released for web development. [2] Java allows programs to be written once and run on any platform, addressing issues with other languages. It also includes tools for building graphical user interfaces. [3] Java programs can be applications, which run independently, or applets, which are executed within a web browser. The document provides a simple example of each.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT 2.

INTRODUCTION TO JAVA

A Brief History of Java

Java began its life in 1990 as a new language called Oak. Sun Microsystems had

established a project group code-named green to develop new products and expand

Sun's markets. Oak was originally designed for a personal digital assistant called *7 that

Sun intended to market with a seamless graphical user interface.

The *7 was never marketed, and eventually Sun formed a company called FirstPerson

to develop the *7 in TV set-top boxes for interactive television. Due to a variety of

circumstances, the promise of interactive TV soon dried up, and Oak was left without a

market. However, about the time that FirstPerson and Oak were failing, the World Wide

Web was exploding. Soon companies such as Netscape began to make software that

would catapult the WWW into the Internet spotlight. Sun soon realized that Oak had

possibilities with the Web, and soon Oak was released to the Internet with a new name:

Java.

Now Java is in its first release as a development environment, and already it is

beginning to influence the direction of computing and the Internet. The Java

programming language is being released free on the Internet, and Sun is licensing the

full implementation of Java and its components to a variety of Internet software vendors

in the hopes of creating a new Web programming standard.


About Java

Java is a very new programming language and makes possible a very new

programming reality. As a commercial product, it is only a few years old, but few new

products have captured the attention of the information science, computer science,

software development, and programming worlds the way this new language has. One of

Java’s most attractive features is that it allows you to write a Java program on an Intel

computer and then run it on a Macintosh without doing anything special, and that truly is

a new programming reality.

In its syntax, Java is very much like another popular programming language: C++.

Unlike C++, however, Java features a number of "building blocks" for creating

Graphical User Interfaces (or GUIs, pronounced gooey), making GUIs very easy to

implement in Java. However, in order to build meaningful GUIs, a programmer needs to

have a grasp of some important programming issues and some fairly complex data

structures, and if you are hoping to acquire that kind of skill, you will need to take other

courses in addition to this one.

Why Java

We are going to use Java to explore basic programming concepts—such as sequential

and iterative execution, simple and complex variables, and program planning. We will

also look at some aspects of the object-oriented programming paradigm, and while

there are three main object-oriented programming languages—C++, Java, and

Smalltalk—we will work only with Java. First of all, Smalltalk is not used by as many
programmers as C++ or Java are, and we have chosen Java over C++ and other

programming languages for a number of good reasons:

 Java is portable—that is, as mentioned above, a Java program written for one

type of machine (say a PC) can easily work on another machine (say a

Macintosh)

 Java applets can run inside a browser. (In this course, we will work primarily with

applets.)

 Java is used widely for writing Internet applications.

Java Applications vs. Applets

Java allows us to write two different types of programs: applications and applets.

 Java applications are computer programs that run like almost any other

computer program. They can be very complex, like the notepad application that

many of you used to build your HTML pages, or they can be very simple. Java

applications are considered "standalones"—which means that they can run on a

computer without the aid of another application, such as a Web browser. Word

processors and spreadsheets as well as Web browsers are all applications.

 Java applets are programs that are executed from within a Web browser. Put

into a Web page, a Java applet can allow users to interact with the page in

interesting ways. For example, if your family owned a carpet store, you might

want to create a simple calculator that would allow users to enter the size of a

room and type of carpet they want, and your carpet calculator would tell them the

number of square yards of carpet they need and the approximate cost of the

carpet and padding. While your Web page could furnish this information in, say, a
table or chart, potential customers might prefer instead to use a calculator applet,

simply because it's easier to use.

Java Applications vs. Applets

Java allows us to write two different types of programs: applications and applets.

 Java applications are computer programs that run like almost any other

computer program. They can be very complex, like the notepad application that

many of you used to build your HTML pages, or they can be very simple. Java

applications are considered "standalones"—which means that they can run on a

computer without the aid of another application, such as a Web browser. Word

processors and spreadsheets as well as Web browsers are all applications.

 Java applets are programs that are executed from within a Web browser. Put

into a Web page, a Java applet can allow users to interact with the page in

interesting ways. For example, if your family owned a carpet store, you might

want to create a simple calculator that would allow users to enter the size of a

room and type of carpet they want, and your carpet calculator would tell them the

number of square yards of carpet they need and the approximate cost of the

carpet and padding. While your Web page could furnish this information in, say, a

table or chart, potential customers might prefer instead to use a calculator applet,

simply because it's easier to use.

Below are two Java examples: one is an applet and the other is an application.

A Simple Java Applet A Simple Java Application


/* /*

NAME: NAME:

SECTION: SECTION:

ASSIGNMENT: ASSIGNMENT:

*/ */

import java.awt.*; public class Hello

import java.applet.Applet; {

public class Hello extends Applet public static void main(String args[])

{ {

public void paint( Graphics g ) System.out.println("Welcome to JAVA!");

{ }

g.drawString("Welcome to JAVA",30, }

30);

g.drawRect(20, 5, 140, 50);

}
There are a couple of major differences between the application and applet shown

above:

While the applet executes g.drawString and g.drawRect, the application executes

System.out.println. This is because the applet runs in a graphical environment—that is, in a

browser. For that reason, it can draw graphical elements in the browser (such as lines,

circles, rectangles, strings, etc.). In this example, it draws the string Welcome to Java

and a rectangle around the string. However, the Java application does not run in a
graphical environment. It has to be run in a DOS window (also called a "console

window") on a PC. The System.out.println instructs the computer to print the text inside the

parentheses to the system's output device. Thus, the message "Welcome to Java!" is

printed to the system's output device--in this case, the DOS window (console window).

There are a couple of import statements in the applet, while there are none in the

application. An import statement makes previously written code available to your

program. In this case, the import statements make available the code that is needed to

draw a string in a browser. In contrast, the simple Java application draws no graphical

elements, and hence it does not need the import statements.

The Java application includes a method called main( ). The main( ) method is

mandatory for all Java applications. When you run the Java application, the machine

looks for its main( ) method, and if it cannot find it, the machine will "complain." Applets

does not need to include a main( ) method—the functionality normally provided by the

main() method is provided by the browser. Remember that a browser is an application

and that applets run inside browsers.

Java Applet in Detail

The table below breaks our example applet into parts and explains its important

concepts.

The actual code What it really means…

/* The slash-asterisk combination ( /* ) signals the beginning

A Simple Java Applet of the comment. From a computer's perspective, a

NAME: comment is a sequence of characters that it will ignore.

From the perspective of the computer's human users, a


SECTION: comment usually consists of statements and information

intended for some purpose, such as making the program's

ASSIGNMENT: code more understandable.

*/ The asterisk-slash combination ( */ ) signals the end of the

comment.

import java.awt.*; These import statements make code from the packages

import java.applet.Applet; java.awt and java.applet available to the applet.

public class Hello extends Everything in Java is written as a class. In this example,

Applet the class is named Hello. This line initiates the definition of

the Hello class.

{ This open brace marks the beginning of the body of the

class Hello.

public void This line initiates the definition of a method called paint( ).

paint(Graphics g)

{ This open brace marks the beginning of the body of the

paint( ) method.

g.drawString("Welcome This calls the drawString( ) method, which is part of the

to JAVA",30, 30); Graphics class. The Graphics class (and, therefore, the

drawString( ) method) is defined in one of the imported

libraries.

g.drawRect(20, 5, 140, This calls the drawRect( ) method of the Graphics class.

50);

} This close brace marks the end of the body and definition

of the method paint( ).


} This close brace marks the end of the body and definition

of the class Hello.


The simple Java applet analyzed above illustrates well the structure of a Java source

file. A typical Java source file (a file with the extension .java) contains a definition of one

class, and the example applet above contains the definition of class named Hello. Java

requires that the name of the class as defined in a source file be the base part of the

source file's filename (that is, part of the name before the extension). In the above

applet, the class name is Hello; therefore, the source file's filename must be Hello.java.

A class definition may contain several method definitions and may (but not

necessarily) be preceded by one or more import statements that give the applet access

to the code in external libraries. The class definition in the above example contains a

definition of a method named paint( ) and is preceded by two import statements. In the

following sections, we will analyze these chief components of a Java program (import

statements, classes, and methods) in more detail.

Import Statements

Java import statements "import" (and, hence, give our applets access to) Java code

libraries that contain code already written to do tasks we might want our applets to do.

Of course, the capacity to import code libraries is not unique to Java: many serious

programming languages have that capacity. Code libraries are simply collections of

previously written classes, methods, and functions that are ready to be executed and

can be used in other programs. The classes, methods, and functions that libraries

contain perform functions that are needed by a variety of programs. Collecting these
elements into libraries provides developers with a set of "building blocks" that are ready

to use.

Java code libraries consist of packages. Each package consists of a number of

previously written classes. For example, java.awt is a package; java.applet.Applet is a

class in the package java.applet. As we see, a name of a package or a class in Java is

a set of words delimited by dots. To use the methods of a pre-built class in our program

we need to import this class using the import statement. We could choose to import a

particular class or a whole package with all its classes. Also, all import statements are

usually specified at the beginning of a program.

Now, let's analyze the two import statements in the applet above.

import java.applet.Applet;

This statement imports the class Applet that is contained in the package java.applet.

The Applet class contains the code that allows us to run our program as an applet in a

Web browser.

import java.awt.*;

This statement imports all classes in the package java.awt (by the way, awt stands for

Abstract Windowing Toolkit). This package contains programs that can build the window

and do the type of drawings we need to do. The asterisk ( * ) that follows the

statement's last period ( . ) is a "wildcard character" and tells Java to import all classes

in the package.

It turns out that the language Java "knows" very little. On its own, it can do a little

arithmetic, allocate memory for data, store data in the allocated memory, make simple

true-or-false tests, and repeat things. That is not much—but that is all a programming
language really needs to be able to do. Whenever we write a program, we need to

decide which parts of the program we should write from scratch ourselves and which

parts can make use of code written by others and made available in libraries. In general,

we want to make as much use of the code available in libraries as possible. This is

somewhat analogous to deciding whether to build a building out of bricks made by

someone else or out of bricks we make ourselves from scratch. Also, be aware that the

library structure for Java is very large and is still evolving, and in this course, we will use

only a few pieces of a few libraries. Therefore, if you want to be a Java programmer,

you will need to learn a lot more about the various libraries than we will cover in this

course.

Classes, Objects, and Methods

Everything in an object-oriented language like Java is written as a class. Class refers to

the structure and behavior of a category of objects. The structure specifies the data that

is contained in the category of objects, while the behavior specifies the actions that can

be performed by the category of objects. The behavior collectively refers to the set of

methods that the class can execute.

An object is an instance of a class. An object is a self-contained entity that has both the

data and the means to act on the data. The example applet and application above each

have one method only (paint( ) in the applet and main( ) in the application), and there

are no structures or data in either of these—at least no data that we can see at the

present.

Now it is time to look at some of the rules for writing Java classes. There is an is-an-

instance-of relationship between an object and its class. As a short form, an is-an-
instance-of relationship is also called an is-a relationship when there is no possibility of

misunderstanding. As we mentioned earlier, a class denotes a category of objects—just

as in English the term Elephant refers to a category of things in the world: elephants.

When we talk about Elephant, we talk in generalities and not about any one elephant in

particular. Similarly, in programming, a class refers to a category of objects and not to a

particular object. For example, a class Elephant describes a category of elephant

objects. An object is-an-instance-of a class. As a convention, when we refer to a class,

we will uppercase the first letter of the class's name, and when we refer to an object, we

will lowercase the entire object name.

In the real world, elephants have attributes such as height, weight, etc. They also do

things such as walk, drink, etc. Similarly, in programming you can define a set of

attributes that a class can have and a set of activities (called methods) that it can

perform.

Class Definition

Classes are the major organizational block for Java programs. A Java program consists

of one or more classes. Within this course, each class is defined in a separate source

file.

The definition of a class specifies what the class has and what it can do. Within a class,

we can import and use other classes. If you look at the first line of the definition of the

class Hello, you will see the following:

public class Hello extends Applet

Let’s look at each of this line's elements—beginning with

public
We can specify a Java class as public, private, or protected using the keywords public,

private, and protected; however, for now we will work only with classes that

designated public. By specifying a class as public, we are saying that the class is

available to be accessed by any code that can access the package in which the class is

declared.

class

The keyword class indicates that the statement is a definition of a class.

Hello

Hello is the name of the class. As we mentioned earlier, class names by convention

should begin with a capital letter—and, as you see, this example follows that

convention. Note: for reasons we won't go into now, you must not change this name.

We will look at these reasons later and show you what you must do if you want to

change this name—but for now, please realize that if you change this name, your

program will probably not run.

extends Applet

Read the phrase extends Applet to mean that the class being defined "descends from,"

"inherits from," or "is a child of" the class Applet. That is, our class Hello is a child or a

subclass of a class named Applet. In turn, class Applet is called the superclass for

the class Hello. This means that Hello can do anything that the parent class Applet can

do. The parent in this case "knows" how to execute itself within a Web page. Since we

have declared our class Hello as a child of Applet, we don’t have to write all of the

needed Java instructions required to run the program in a Web page. Class Hello

inherited this ability from its parent class Applet. In Java, the mechanism by which a
child class acquires functionality defined in a parent class is called inheritance. There

are other methods in class Applet that class Hello can inherit and use. Some of these

methods are init( ), start( ), stop( ), and update( ). Notice that our class Hello has its

own paint( ) method. This is fine—Java will use our definition of paint and ignore the

definition of paint( ) in the class Applet. If we leave out a definition of a method, Java

automatically relies on the parent's definition.

The following is the body of the Hello class:

public void paint( Graphics g ) {

g.drawString("Welcome to JAVA",30, 30);

g.drawRect(20, 5, 140, 50);

This class body is bounded by or delimited by a pair of braces. The last character of the

class must always be a closing brace ( } ). All of the Java code found within these brace

delimiters is part of the class.

Methods and Method Definitions

There are two main components of a Java class:

1. data (also called the structure)

2. methods (also called the behavior)

All of the structure (data) and behavior (methods) of a class have to be defined in the

body of the class. That said, as you may have noticed, there is no data stored in the
Hello example class. However, there will be data in some of our future programs, but

that will have to wait for a while.

In Java, methods are groups of instructions that have names. Methods enable our

programs to do things. Note that other languages use other terms to refer to what in

Java we call methods. In Fortran, the term is subroutine; in Pascal, it is procedure; in C,

it is function; and in C++, it is member function.

In order to have the computer execute the instructions in the body of one of our

methods, the method must be invoked or called. We have a very interesting situation

when we write applets: some of our methods are called for us automatically when we

run the applet—and others are not. For example, the paint( ) method is called

automatically when we start the applet and is called anytime it is needed.

Inside the body of class Hello, the first thing we see is a definition of a method named

paint( ). The method definition consists of the method's name, followed by a set of

parentheses. Sometimes these parentheses will contain parameters. A parameter is a

piece of data that is provided to the method when that method is called. After the

parentheses is the body, enclosed in braces.

Let's dissect this method:

public void paint( Graphics g )

The keyword public tells Java that this method can be used by other classes outside of

the class Hello. Remember that somewhere, somehow, our paint( ) method is called for

us automatically—so our method paint( ) must be defined as publicly accessible—

otherwise our applet will not be able to run. For now, all of our methods will be defined

as public. 
The keyword void means that a method does not return a value. Methods can do three

things:

They can draw.

They can compute and return values, such as an average of a list of numbers.

They can do both of the above.

For now we will use only void methods—these are methods that do things but do not

return values. Following the keyword void is the method name: paint( ).

(Graphics g)

Following the method name in our example is a list of parameters enclosed in a pair of

parentheses. This is the list of resources the method needs to do its job. Some

methods, however, need no parameters at all, and, therefore, feature a set of empty

parentheses—a method definition must have the parentheses, even if the parentheses

are empty. However, in our example, the parentheses contain one parameter: g.

The "Graphics" inside the parentheses is the name of a class defined in one of the

imported libraries (the fact that it is capitalizes clues you in to the fact that it is a class,

since the convention is to capitalize class names). By writing "Graphics g", we are

indicating that g is an object of the Graphics class. Note here that since the parameter

we are specifying is to be an object of the Graphics class, we must specify the class

name "Graphics" exactly as it is shown above, but the object name can be anything we

choose. Here we give it the name g, but we just as easily could have named it gr or

myGraphicsObject or any other meaningful name. Any object of the class Graphics

"knows" how to draw things in an applet window, how to change color, and how to print

words. By placing this parameter in the parentheses, the method paint( ) is being given

a resource—an object named g of the Graphics class—which knows how to draw. The
paint( ) method can now use this object to draw things in the applet window. It is very

similar to me asking you to write something for me on a piece of paper and loaning you

my pen to do it. The loaning of the pen is very similar to putting "Graphics g" in the

parameter list.

The body of the method is delimited by a pair of braces, just as the body of the class is.

Everything within this set of braces is part of the paint( ) method. You can define

methods within classes, but you cannot define classes within methods, and you cannot

define methods within methods.

Inside of the body of paint( ) there are two statements. The first statement draws a

string "Welcome to JAVA" at the location x:30, y:30:

g.drawString("Welcome to JAVA", 30, 30);

The next statement given below draws a rectangle 140 pixels in length and 50 pixels

high at the location x:20, y:5:

g.drawRect(20, 5, 140, 50);

Four steps in Creating a Java Applet

1. Write Java code that will constitute the applet. To write code, you will use

an editor. You will save the Java code in a source file ( .java file). Note that all

java source files should have a .java extension. Furthermore, the file in which you

put the source code for a class should have the same name as the name of the

class extended with .java. In the above example, the class Hello should be placed

in a file named Hello.java.

2. Compile the Java source code in the .java file into bytecode using a Java

compiler such as javac that is a part of Java Development Kit (JDK). The result of
compilation will be a bytecode file. Note that all bytecode files will have the

extension .class. In our example, the bytecode file generated from the source file

Hello.java will be named Hello.class.

3. Create a HTML file that embeds this bytecode file in a pair of APPLET tags that

specify

 the location of the Java applet

 the size (that is, the width and height) of the area occupied by the applet in

the browser or applet viewer.

4. Run the applet by opening the HTML file in a Web browser or an applet viewer—

a special "minimal" browser for running applets that is also included in Sun's JDK.

Note that the steps necessary to run a Java application are slightly different. Below is a

diagram of the process of compiling and running a Java application. After compiling

your application's source file with the javac compiler, you will get a .class file. This .class

contains the Java application. You will run this .class file using the JDK Java

interpreter called java. Web browsers and applet viewers can't run Java applications.
Pay particular attention to the following when creating an Applet:

 Spelling.

 The case of letters. Java treats "import" and "Import" as different words—if you

type "Import", your program is wrong!

 Matching sets of parentheses ( ) and braces { }. These are called delimiters and

must come in opening-closing pairs.

 The punctuation marks. In this program they include the period ( . ), semicolon ( ;

), quotation mark ( " ), and comma ( , ).

 Special symbols. These include the asterisk ( * ) and slash ( / ).

Source code is the program written in Java or other high-level programming language

by the programmer. Source code can be read by humans. Source code is stored in

source files. The Java program you saw in the previous page is the source code of the

Hello applet.

Compilation is the process of converting high-level source code into machine language

or another form that can be executed by the machine. While high-level source code can

be easily understood by humans, the low-level machine language is a form that is

extremely strenuous for humans to follow, while extremely easy for machines to

interpret.

Compiler is a computer program that performs compilation. In our course, you will most

likely be using a Java compiler named javac that is a part of the Java Development Kit

(JDK). There is more help on installing and using JDK in the appendix section on setting

up your Java environment.


From your Command Prompt window (also called a DOS console window), you can call

the Java compiler javac to compile the source code file Hello.java with the command:

javac Hello.java

Compiling a Java source file produces a bytecode file. Bytecode is a special

intermediate-level format that can be run by the Java Virtual Machine. Files that contain

bytecode have a .class extension. When you compile Hello.java using the Java compiler

javac, it produces the bytecode in a file called Hello.class in the same directory. This file

is written and named by the Java compiler, and its name is always the same as the

name of the class defined in your Java program with a .class extension appended. The

result of a successful compilation of your Java program is always at least one .class file.

Bytecode is not a low-level machine code. It can't be directly executed by your

computer. Bytecode has to be executed by the Java Virtual Machine, or JVM. Although

JVM has the term machine in it, the machine refers to a software implementation—that

is, an abstract machine. When your bytecode is run inside the JVM, the bytecode is

translated into real machine code that can be run by the physical machine. All Java

interpreters, Java-enabled browsers, and applet viewers have a JVM inside and can

execute bytecode. The JVM acts as an intermediary between the real computer and

your bytecode. By having a two-level architecture with bytecode as intermediate-level

representation and the JVM acting as an abstract machine, Java achieves portability

across computer platforms. That is, you can run your bytecode on a Sun computer or a

Macintosh computer, or any other computer that has a JVM implementation. Currently,

JVM is implemented for most existing computer platforms.


Creating the HTML File

A Java applet is invoked (run or executed) from within a Web page. A call of an applet

has to be embedded inside some HTML document. Here is the simplest form of an

HTML document that will run our applet Hello. Convention dictates that you name this

file Hello.html, but that is just convention and not a Java rule (unlike the case with

Hello.java).

<HTML>

<BODY>

Here is the Hello applet:

<APPLET code = "Hello.class"

width = 200

height = 75>

</APPLET>

</BODY>

</HTML>

The APPLET tag in the HTML file "tells" the applet viewer or Web browser three pieces

of information:

code = "Hello.class"

width = 200

height = 75

The first list item literally says that the applet to be executed is called "Hello.class". As

you remember, javac created Hello.class from Hello.java when you compiled the

Hello.java program.
The second and third list items tell the browser or applet viewer how big the applet

window must be. When a Web browser or the applet viewer executes or runs your

applet, it builds a window 200 pixels wide and 75 pixels high and executes the bytecode

instructions in the file Hello.class. The unit of measure is pixel, which is short for picture

element. The graphics display for your computer is composed of thousands (or millions)

of these individual elements; thus the pixel is the smallest piece of visual information

that your monitor can display. It is about the size of a period ( . ), like the one at the end

of this sentence.

Running the Applet

Running the applet is done by using a Web browser or the applet viewer provided by

Sun as a part of the JDK. An applet viewer is a special program that could run applets.

It could be considered a stripped-down Web browser that can't display HTML, but can

locate an applet inside a Web page and run it. Both the browser and the applet viewer

require an HTML document that invokes or embeds the applet.

All browsers that are java enabled (that is, they include the JVM) can understand and

execute your bytecode. And most popular browsers such as the Internet Explorer and

Netscape Navigator are Java enabled. This is one of the reasons for the remarkable

popularity of Java. However, different browsers have slight variations in the way they

execute applets. We suggest that you use an applet viewer provided with your JDK as

the definitive tool to check your work.

Components of a Java Applet

The typical Java applet is made up of numerous components that include keywords,

identifiers, statements, classes, methods, and control structures.


Keywords

Keywords are words that have a special meaning in the Java language. Keywords are

used to form different programming constructs..

abstract boolean break byte case catch char class


const continue default do double else extends final
finally float for goto if implements import instanceof
int interface long native new package private protected
public return short static strictfp super switch synchronized
this throw throws transient try void volatile while

The applet listed earlier in this page contains the following keywords:

 import - is used to make parts of a library available for use in the current

program.

 public - means that other classes may use this class or method during their

execution.

 class - tells Java that this is the beginning of a class declaration.

 extends - tells Java that the class named before the keyword extends is a

subclass of the class named after the keyword. (For example, the code " public

class Hello extends Applet" tells Java that Hello is a subclass of Applet.)

 void - means that this method will not return a value.

Identifiers

An identifier is a name. In Java, an identifier can be a class name, a method name, or a

parameter name. For example, the class name Hello is an identifier. Similarly, the name

of the parameter g is also an identifier—and so is the method name paint.


The syntax of identifiers is very important. Identifiers can use alphabetic characters of

either case (a–z and A–Z), numbers (0–9), underscores ( _ ), or dollar signs ( $ ). No

other characters are allowed. No commas, hyphens, etc. Also, identifiers cannot start

with a number. Finally, keywords cannot be used as identifiers (for this reason keywords

are sometimes called reserved words).

The following are valid The following are not valid


identifiers identifiers
4pie pie-pie pie,pie
student pie_Master
pieMaster pie4 pie2pie
pie/cake method void
dollar$man $dollarman
pieMethod

Statements

Statements are the basic units of execution in a program. They tell Java to do

something. This program has the following statements:

import java.applet.*;

import java.awt.*;

g.drawString("Welcome to JAVA", 30, 30);

g.drawRect(20, 5, 140, 50);

These statements result in some action being performed. Some of the actions

are invisible to the user of the applet. The user will never actually see the import

statements being executed because they are directives to the compiler. The g.drawString

statement will result in a visible action because the string Welcome to JAVA will be
displayed in the applet window. Statements have one thing in common—they end with a

semicolon ( ; ). Where there is no semicolon, there is no statement.

The body of the method paint( ) in our example has two statements:

g.drawString("Welcome to JAVA", 30, 30);

g.drawRect(20, 5, 140, 50);

Finding and Fixing Errors

When you modify the Java program, you may encounter some errors when you compile

it. We will soon learn what those errors mean and how they can be fixed. Sometimes it's

a matter of a missed comma or semicolon.

In all disagreements with the compiler, the rule is simple: the compiler always wins. The

author typed in the Hello Java applet program and left out the semicolon at the end of

the second line shown below—the "_" is where the missing semicolon should be:

import java.awt.*_

Here's what was typed on the command line (it was supposed to compile a Java

program):

>javac Hello.java

And here are the error messages issued by the compiler:

Hello.java:6: ';' expected. Format: filename:line

number:message. This error message

indicates that it has detected a

problem on line number 6: a missing

semicolon.
import java.awt.* Here the compiler displays the line of
code where the error might be.
^ The compiler then places a caret ( ^ )

under the line of code where the error

might be.
Hello.java:8: Superclass Applet of class A second error message—this one

Hello not found. flagging line number 8 as a possible

location of an error. But, beware, there

is actually no error on line 8!!!


public class Hello extends Applet Again, the compiler displays the line of

code where it thinks the error is.


^ Again, compiler places a caret ( ^ )

under the line of code where the error

might be.
2 errors This is the total number of errors

found.
Now, if a semicolon is put in line 6, where it belongs, both of these errors will disappear.

As indicated above, the basic message format gives the file name and then the number

of the line on which the error might be located. Just remember that the error message

represents the compiler's best guess at what is wrong. The best way to get introduced

to Java error messages is by experience. Your initial exposures will probably be

frustrating, but that will pass. Once you have corrected all of the errors, you can run

your program in applet viewer or Web browser.

Errors are a part of a programmer's life—we all make them. It turns out that writing a

program takes a much higher degree of perfection than most of us are used to

achieving, and the simplest error can keep our programs from running. And once our
programs run, we must continue evaluating and testing them to make sure they are

running correctly. Some programs are so complex that they defy complete testing for

correctness. Fortunately, you will not write such programs in this class, but some of the

ones you will write will be difficult to test exhaustively.

When you wrote Web pages in the previous unit, you probably made two types of

errors:

 syntax errors

 execution errors

Syntax errors occurred when you used the wrong tag or left out a closing tag or a

closing angle bracket. A syntax error would cause angle brackets to be displayed in

your Web page when viewed in a browser. The fact that the Web page is displayed at

all is due to the fact that the browser ignores HTML syntax errors and displays the page

regardless.

You can think of syntax errors as errors in grammar. Just as grammatical errors in

English lead to ill-formed sentences, syntax errors in programming lead to ill-formed

programs. Humans are smart enough to infer the meaning of a sentence, even if the

sentence is ill formed. But, compilers are not that smart. They will complain, and you

have to fix the error.

Execution errors are also called "logical errors." For example, maybe you wanted

something displayed as bold or centered, and that something was instead displayed as

italic or left justified—that is an execution or logical error. The browser did what it was

told to do, and the syntax of the HTML was correct, but the result was not what you

wanted. There is a story about a king who intended to spare the life of a particular
prisoner, and one day when the king's jailer sent him a letter asking, "What do you want

to do with this prisoner, kill or spare him?", the king, being pressed with many other

matters, wrote back a terse reply. Unfortunately, although the king had intended with his

reply to order the prisoner's life spared, in his haste to write "Kill not, spare" he

misplaced the comma and wrote "Kill, not spare." Thus, the king's statement illustrates

what we have called a "logical error." The statement is grammatically correct, and the

jailer could, therefore, understand and obey it as an answer to his question; but it did

not accomplish what the king had intended, because the prisoner was killed. When you

write programs, you will most likely also run into such logical errors (though not as fatal).

You should test your programs to see if they do what you intended them to do. Again,

execution errors are not errors in grammar: if the king's grammarians had examined his

statement, they wouldn't have found an error. Similarly, a compiler (which is a type of

grammarian) will not usually complain about logical errors; logical errors usually

manifest themselves at run time, not compile time.

Both of these types of errors (syntax and logical) can also occur in a Java program.

However, Java is somewhat pickier about syntax. Your browser never refused to display

your Web page—it just ignored your syntax errors. In fact, a syntax error that causes a

very bad display in one browser may not cause a bad display on another browser; this

is why you must test your Web pages on different browsers.

If you have a syntax error in a Java program, it will not compile—and Java will output a

list of cryptic error messages. Once you have decoded the error messages and fixed

the errors (more evaluation/testing, planning, and coding) you will have eliminated the

syntax errors. Then you must run the applet to see if it does what you intended it to do.
Four final thoughts about syntax errors:

1. The Java compiler will provide, at best, a guess of what the error is and where it

occurred. Sometimes it is correct and shows you where to fix the error.

Sometimes it will mark a place that contains no error. If you find no error visible,

check the code above the marked line. You may have made a mistake one, two,

or more lines above the indicated place.

2. If the Java compiler prints a long list of errors, you should consider only the first

one or two to be truly valid. It is possible that the first syntax error led the

compiler down a very wrong path to find other errors that are not really errors at

all. Fix the first one or two errors and recompile your program. You may find that

the other errors are no longer in the list.

3. The opposite of item two can occur. You compile and get two errors. You fix

them, and the next compile generates twelve errors. What happened? Java

found the first two errors and for various reasons stopped compiling the program.

Java literally "did not see" the rest of the errors. Once you fixed the first two

errors and recompiled, Java was able to "see" the next set of errors. This leads

to one major piece of advice that will be important to you when you write your

first original program: compile frequently and fix the errors as you go. It is usually

not a good idea to write an entire program from the opening comment to the last

"}" and then start compiling it for the first time. Seeing a list of 354 errors can be

very depressing.

4. If you read an error message and it makes no sense, get help. If you read an

error message and understand it but cannot find the actual error, look again. If
you spend more than 2–3 minutes in this state, get outside help. Ask your

teacher, or, if it's allowed, ask another student to look at your code. Just staring

at code rarely helps you find errors. Get help—an outside pair of eyes can find

things at a glance that you, as the original author, might never see.

Commenting Your Code

Documenting code is one important task for which software developers are responsible.

One element of documenting code correctly is including comments within the code.

Commenting code is very important because it makes the code easy to maintain thus

making the software's total cost of ownership less expensive than it is for code that is

not well commented. When code is well commented, it is less costly to maintain

because any developer who is maintaining it requires less time to understand the code’s

purpose and how the code works.

When you are writing comments, you should assume that the reader of the comments

will be a developer of average competence who knows nothing about the class’s

purpose or how the code functions. Well written comments should explain the purpose

of the class somewhere near the beginning of the class. Each method should have at

least one comment placed immediately before the method name explaining the purpose

of the method and how the method performs its function. Any complicated approach

that you used to accomplish the method’s function should be brought to the attention of

the reader in order to minimize the time required by the developer to understand how

the code functions.


All of the classes that you submit should be commented. Comments can be created in

two ways. One method that can be used to create a comment is to begin the line of

code with a “//” symbol. Two examples follow.

// The purpose of this class is to compute the average of two numbers.

Or,

average = (num1+num2)/2; // computes the average of two numbers.

In the above examples, all text appearing after the “//” AND on the same line will be

considered to be a comment. This approach is typically used when the comment is

short in length. Comments are not compiled when the class is compiled. Comments are

not considered to be java statements. If the comment wraps to a new line and that line

does not begin with a “//” symbol, the compiler will not treat it as a comment and a

compile error will be generated. Sometimes the comment is placed immediately before

the line(s) of code that it is intended to document, as shown in the first example above,

and sometimes the comment is placed on the same line as the line of code that it is

intended to document, as shown in the second example above. Either approach is

acceptable.

Sometimes, a comment that spans several lines is needed. In this situation, the

comment can be created by beginning the comment with a “/*” symbol and ending it

with a “*/” symbol. For example,

/*

 This class accepts from the user a name to display and a color in which to display it.

Upon accepting the user's input, the value of the name is stored in a variable called

strName and the value of the color is stored in a variable called strColor. Then the paint
method is called to display the output.

*/

In the above example, all text between the ‘/*' symbol and the ‘*/' symbol is a comment.

Graphics and Variables

java.applet

- Provides the classes necessary to create an applet and the classes an applet

uses to communicate with its applet context.

java.awt

- Contains all of the classes for creating user interfaces and for painting graphics

and images.

java.awt.event

- Provides interfaces and classes for dealing with different types of events fired by

AWT components.

Applet class

- must be the superclass of any applet that is to be embedded in a Web page or

viewed by the Java Applet Viewer.

- provides a standard interface between applets and their environment.

Class Applet
java.lang.Object

+--java.awt.Component

+--java.awt.Container

+--java.awt.Panel

+--java.applet.Applet

init - public void init()

Called by the browser or applet viewer to inform this applet that it has been loaded into

the system. It is always called before the first time that the start method is called.

A subclass of Applet should override this method if it has initialization to perform. For

example, an applet with threads would use the init method to create the threads and the

destroy method to kill them.

start - public void start()

Called by the browser or applet viewer to inform this applet that it should start its

execution. It is called after the init method and each time the applet is revisited in a Web

page.

A subclass of Applet should override this method if it has any operation that it wants to

perform each time the Web page containing it is visited. For example, an applet with
animation might want to use the start method to resume animation, and the stop method

to suspend the animation.

stop - public void stop()

Called by the browser or applet viewer to inform this applet that it should stop its

execution. It is called when the Web page that contains this applet has been replaced

by another page, and also just before the applet is to be destroyed.

A subclass of Applet should override this method if it has any operation that it wants to

perform each time the Web page containing it is no longer visible. For example, an

applet with animation might want to use the start method to resume animation, and the

stop method to suspend the animation.

destroy - public void destroy()

Called by the browser or applet viewer to inform this applet that it is being reclaimed

and that it should destroy any resources that it has allocated. The stop method will

always be called before destroy.

A subclass of Applet should override this method if it has any operation that it wants to

perform before it is destroyed. For example, an applet with threads would use the init

method to create the threads and the destroy method to kill them.

paint - public void paint(Graphics g)

Paints the container. This forwards the paint to any lightweight components that are

children of this container. If this method is reimplemented, super.paint(g) should be

called so that lightweight components are properly rendered. If a child component is

entirely clipped by the current clipping setting in g, paint() will not be forwarded to that

child.
Overrides:

paint in class Component

Parameters:

g - the specified Graphics window

update - public void update(Graphics g)

Updates the container. This forwards the update to any lightweight components that are

children of this container. If this method is reimplemented, super.update(g) should be

called so that lightweight components are properly rendered. If a child component is

entirely clipped by the current clipping setting in g, update() will not be forwarded to that

child.

Overrides:

update in class Component

Parameters:

g - the specified Graphics window

repaint - public void repaint()

Repaints this component.

This method causes a call to this component's update method as soon as

possible

Defining Classes

public class classname

{
Declaration of instance variable1;

Declaration of instance variable2;

... Declaration of other instance variables ...

Definition of method1

Definition of method2

... Definition of other methods ...

Comments and White Space

Remember that Java ignores white space—such as blanks, tabs, empty lines, etc.—

between words in programs. Note that white space inside a string (anything inside a pair

of quotation marks is a string) are not ignored. Example: "This is a string".

Also note that anything in a line that comes after a pair of slashes ( // ) is a comment.

Comments are for the human reader, and the Java compiler will ignore them. Thus,

when the compiler sees a pair of slashes, it ignores the rest of the line. You can also

mark something as a comment by enclosing it between a slash-asterisk ( /* ) and an

asterisk-slash ( */ ). Anything that falls between the comment delimiters /* and */ will be

ignored by the compiler.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy