Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Schongar P.VBScript unleashed.1997

.pdf
Скачиваний:
43
Добавлен:
23.08.2013
Размер:
1.59 Mб
Скачать

Chapter 18

VBScript and Java

by Ramesh Chandak

CONTENTS

What Is Java?

Java, Java Applets, and JavaScript

Java Classes

JavaScript Objects

JavaScript Language Structure

JavaScript Operators

JavaScript Flow of Control Statements

VBScript Language Structure

VBScript Examples

VBScript Variables

VBScript Operators

VBScript Err Object

VBScript Variant Data Type

VBScript Constants

VBScript Flow of Control Statements

VBScript Functions

VBScript Procedures

ActiveX

Standards and Conventions

Comparing Java, JavaScript, and VBScript: A Summary

Examples

Relevant Web Sites

Review

Among all the Internet buzzwords you hear today, I am sure one of them has been Java. What is Java? Why is it so hot? What is all the hype about? Why is everyone saying Java has revolutionized the computer and information industry? Where did it come from? If Microsoft didn't make it, who did? All this and much more. Never before has the computing industry undergone such a transformation in so little time. First the Internet, then Netscape Navigator, and now Java! The Internet has completely changed the development and distribution paradigm.

Java is a product from JavaSoft, the software division of Sun Microsystems. With the advent of browser technology and Web authoring tools, creating and navigating the Web pages has become very easy. But these pages have been mostly static, with very little or no interactivity, as if they had no life of their own. They were straight rendering of text and graphics. Static pages generate very little interest for the surfer. There was a need for something that would liven up the experience of surfing the Internet. Then comes along Java!

What is Java? Java is an object-oriented programming language. Java is multithreaded, secure, and portable. It is based on C++, the object-oriented programming language that has been in use for several years now. You can create portable, interactive Web pages using Java. The Java Virtual Machine (JVM) is the core of the Java runtime system. It is a software-based microprocessor and translates Java executables into platform-specific instructions. Java code itself is machine-independent, but JVM is not. JVM is machine-specific. The Java compiler compiles your Java program into compiled bytecodes. A bytecode is a runtime form that executes on the JVM. The extra layer of JVM makes Java programs sluggish compared to native programs written in C or C++. Java applications are portable because of the JVM implementation but are comparatively slower. Just-In-Time (JIT) compilers have addressed this issue. A JIT compiler compiles the bytecodes into native code on-the-fly. It acts as the intermediate layer between the JVM and the target machine. A Java-enabled browser means the JVM is built into it. When the browser comes across the <APPLET> tag, it downloads and executes it using its built-in JVM.

Java and JavaScript are different. Java is an object-oriented programming language. JavaScript is an object-based scripting language. Using Java, you can build standalone applications and applets. Using JavaScript, you cannot build Java applications and applets. JavaScript, originally called LiveScript, is a technology from Netscape. Java is a technology from Sun Microsystems. JavaScript can be considered an extension to HTML. HTML is good for straight rendering of text and graphics, but lacks the capability to make the surfing experience interactive. There are certain things you cannot do using pure HTML-for example, validating user response. Using just HTML, you would have to use CGI scripts or programs at the server end to process and validate user responses and return the results to the browser. Using JavaScript, you can do this directly within HTML without having to send the data back and forth. This reduces network traffic and improves overall response. Only validated data is sent to the server. You can do much more with JavaScript. You can add animation to your Web pages. You can display alert windows and message boxes if the user does not enter the correct data or correct format of the data. Simply put, you can build interactive Web pages using HTML and JavaScript.

According to a recent ComputerWorld survey, there are approximately 3 million programmers around the world (and still growing!) who use Visual Basic as their primary programming language. On the other hand, there are approximately 1.1 million programmers who use C/C++ as their primary programming language. Those 3 million programmers would benefit from VBScript, Microsoft's scripting language for the Web. Because VBScript is a subset of Visual Basic, these programmers would find it easy to use. Most of all, VBScript would benefit the non-programmers, whose background is not strictly programming. Non-programmers who are interested in creating their own interactive Web pages would find it easy to program using VBScript since the programming structure is based on the BASIC language. The VBScript learning curve would be a lot shorter compared to JavaScript for a non-programmer.

It is important to understand that both JavaScript and VBScript have their advantages and disadvantages. Java is portable and object-oriented. VBScript is not truly object-oriented. Unless you are an expert in object-oriented and C++ programming, Java involves a steeper learning curve.

Scripting using VBScript and JavaScript is easier than programming in C and C++. Take a look at the HyperCard community for the Macintosh. The introduction of HyperCard and its scripting language, HyperScript, revolutionized the Macintosh world of programming. A whole new generation of applications has been developed by a variety of peopleboth programmers and non-programmers.

As of this writing, only Microsoft Internet Explorer 3.0 supports VBScript. In contrast, JavaScript is supported by Netscape Navigator 3.0, Microsoft Internet Explorer 3.0, and HotJava 1.0, Sun Microsystem's browser.

This chapter introduces Java and its features, as well as JavaScript and its programming syntax and structure. It also discusses Java applets and Java classes. It further discusses VBScript and its syntax and structure. After reading this chapter, you will have gained a good understanding of Java, JavaScript, and VBScript, and how they compare with each other. This chapter is not a programming reference guide on JavaScript and VBScript. It does not include all the programming structures and conventions available in these scripting languages. Instead, it discusses the main features of each language, including functions, subroutines, arithmetic, and logical and comparison operators, and compares and contrasts them. This chapter also discusses a Web page example written using both JavaScript and VBScript. By comparing both the scripts, you will gain a better insight into these languages.

What Is Java?

Java is an object-oriented programming language. Java includes a runtime interpreter, an Application Programming Interface (API), and a set of development tools. Java is distributed as JDK-the Java Developer's Kit. As of this writing, the latest version of JDK is 1.1. You can download JDK from JavaSoft's Web site: http://java.sun.com. Figure

18.1 shows the JavaSoft home page.

Figure 18.1 : Java home page hosted by JavaSoft, the soft-ware division of Sun Microsystems. It is one of the most

popular Web sites, visited by millions of programmers, developers, and others.

Java is secure. Java is multithreaded. Java is derived from C/C++. If you are an experienced C/C++ programmer, you will find it easy to get started with Java. It includes the Java Application Programming Interface-a library of methods for developing platform-independent, distributed applications that include full networking and windowing support.

NOTE

If you are an experienced C++ programmer, you will appreciate Java and its features, including built-in networking, platform-independent API class library, and robust exception handling. When programming in Java, you no longer have to deal with pointers. Java understands object-oriented structure only. Everything you define and use in Java must be an object.

Figure 18.2 shows the Java development framework. The Java source code utilizes the Java API and user-defined classes. The source code is compiled into Java runtime bytecode by the Java compiler. The runtime bytecode runs on the Java Virtual Machine (JVM), a software-based microprocessor. The JVM is an interpreter and can reside on any platform, including Windows 3.1, Windows 95, UNIX, Macintosh, and so on, thus making Java applications platformindependent.

Figure 18.2 : The Java Developer's Kit (JDK). Java is distributed as the JDK. The JDK includes the runtime interpreter,

the Java Virtual Machine (JVM), and the Java API.

The Java Developer's Kit contains a variety of tools and Java development information. Following is a list of the main components of the JDK:

The Runtime Interpreter

The Compiler

The Applet Viewer

The Debugger

The Class File Disassembler

The Header and Stub File Generator

The Documentation Generator

Applet Demos

API Source Code

The Java API includes class definitions and methods that provide links into the native windowing and networking capabilities of the host operating system. It is the common thread between Java programs and any host operating system. The Java runtime system and API make Java portable. The Java runtime system is not tied to any particular operating system. It has been developed from scratch. The Java API is a universal API for writing applications targeted at all operating systems.

Java is supported by both industry standard browsers-Netscape Navigator and Microsoft Internet Explorer. There are

several applications that have been written using Java. HotJava, Sun Microsystem's Web browser, is written completely using Java. You can develop a variety of applications using Java. Using Java you can write multithreaded applications and secure, distributed, multiplatform applications. You can also write object-oriented Web applications. You can write applets using Java. An applet is not a standalone application; it cannot run on its own. A browser or an applet viewer needs to be used to run an applet. When the browser encounters the <APPLET> tag, it downloads the applet and the JVM embedded within the browser executes it.

Figure 18.3 describes the Java API structure. The Java API consists of two types of packages: packages that are built-in and packages that a Java programmer can define and use.

Figure 18.3 : Java API consists of packages. It comes with a predefined set of packages. You can also define your own

packages.

A Java package is a group of related interfaces, classes, and exceptions. The grouping is done simply for ease of understanding and convenience. See Figure 18.4.

Figure 18.4 : A Java package includes interfaces, classes, and exceptions.

Java is object-oriented. Anything you define and use must be an object. A class is the basic object-oriented component in Java. An interface is a collection of related methods. An exception is an event that alters the normal course of program execution.

Class: A class is the basic object-oriented component in Java. It includes methods and variables. Variables store data. Methods are functions that operate on the classes and variables. For example, the checkbox class in the java.awt package is used to implement checkbox and radio button GUI controls in Java applications. The file class in the java.io package is used to provide systemindependent access to a file or a directory on the host operating system. The applet class in the java.applet package is used to implement Java applets.

Interface: An interface is a collection of related methods. For example, the imageproducer is a set of functions for classes that produce images. The imageproducer methods are used to reconstruct or modify an image being produced.

Exception: An exception is an event that alters the normal course of program execution.

The Java Developer's Kit comes with a number of examples. Figure 18.5 shows a tic-tac-toe example, written as a Java applet and executed using Microsoft Internet Explorer.

Figure 18.5 : The tic-tac-toe Java applet. It comes with the JDK. The JDK can be downloaded from Sun's home page:

java.sun.com.

The file tictactoe.java on the enclosed CD-ROM includes the source code for the tic-tac-toe Java applet.

Java, Java Applets, and JavaScript

A Java-enabled browser means the Java runtime interpreter and Java Virtual Machine are integrated within the browser. Applets are Java programs that are linked to the Web browser. An applet may be used to enhance a Web document by displaying animation or playing sound. It cannot modify the state of the HTML document being displayed. It is executed by the Java runtime interpreter that is integrated with the browser.

An applet is specified by the <applet>... </applet> tags within the HTML code. When the browser encounters

the <applet> tag, it downloads the applet, runs a number of security tests on it and passes it to the runtime interpreter and Java Virtual Machine that execute it locally. Applets are executed within a well-defined area of the browser. It is similar to running a command-line program. The browser does not execute the applet. The runtime interpreter executes the applet. You can think of the runtime interpreter as a plug-in or helper application to the browser.

Java and JavaScript are not the same. Nor are they competitors to each other. Java is an object-oriented programming language. JavaScript is a scripting language. You can use Java to write object-oriented, network, distributed, secure, multithreaded Java applications. The source code files have .java extensions. Java source code is compiled and stored in .class files. See Figure 18.6.

Figure 18.6 : The Java source code is stored in .java files. The compiled code is stored in .class files.

JavaScript is embedded within your HTML code. It is an extension to your HTML code. You can change the appearance and behavior of your Web pages dynamically using JavaScript. You can process mouse events such as mouse click or the mouse moving over a certain part of the Web page and initiate certain actions on such events. For example, you can display different background bitmaps, depending on the day of the week. You can process form data when the user clicks the submit button and alert the user of any invalid data. Java supports static binding. When writing code using Java, you must declare the types of variables before you can use them. JavaScript supports dynamic binding. With JavaScript it is not necessary to declare the type. If you do not declare the type of the variable, JavaScript interprets it at runtime, based on the context in which it is used. For example, if a variable is used to perform addition of numbers, it is interpreted as a number. If a variable is used to perform string concatenation, it is interpreted as a string. Such loose binding makes JavaScript lightweight and portable. Similarly, if you declare functions in JavaScript, it is not necessary to specify the type of the return value of the function. On the other hand, you must declare the type of the return value of the function in Java. Java applets can also be executed using any of the three browsers. Java is available as JDK from JavaSoft's Web site. If you download and install Netscape Navigator, Microsoft Internet Explorer, or HotJava, you have basically everything you need to use JavaScript.

NOTE

You can use Java to develop non-Web-based applications. Since JavaScript and VBScript are extensions to HTML, they are used primarily to create Web applications. However, VBScript can be used as a component in other Windows applications.

Listing 18.1 shows a HelloWorld program written in Java.

Listing 18.1. A HelloWorld program written in Java.

import java.lang.System;

class HelloWorld {

public static void main (String args[]) {

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

}

}

Compare the preceding Java code to JavaScript and VBScript code for writing the same HelloWorld program. Listing 18.3 shows an example of a HelloWorld program written in JavaScript.

Java Classes

The Java API includes the following packages. A Java package includes interface, classes, and exceptions.

java.net:

A library of classes and methods for implementing socket-based

 

client/server networking

java.io:

A library of classes and methods for stream-based I/O

java.applet:

A library of classes and interfaces for applet development

java.awt:

A library of windowing classes and methods called Abstract

 

Windowing Toolkit (AWT)

java.awt.image:

A library of classes for managing image data, including color

 

models, cropping, and color filtering

java.awt.peer:

A library of interface definitions that map platform-independent

 

AWT classes to their native platform-dependent

 

implementations; it does not include any classes

java.lang:

A library of methods and classes for applet, console, and window

 

programming

java.util:

A library of Java utilities

sun.tools.debug:

A library of debugging tools and utilities

NOTE

To keep abreast of the latest on Java, visit Javasoft's home page regularly.

JavaScript Objects

JavaScript is an object-based scripting language. Even though it is object-based, JavaScript does not support inheritance. You can define your own objects in JavaScript and use them together with JavaScript's built-in objects to write Web pages. As of this writing, there are a total of 17 JavaScript objects. Table 18.1 lists them.

 

Table 18.1. JavaScript objects.

Object

Meaning

navigator

Base class for all HTML objects

window

Base class for the document object

document

Contains information about all HTML properties inside the current

 

page

history

Contains browser's URL history list

form

Contains information about the defined form

date

Contains date information, including system date function

math

Includes math constants and functions

string

Contains information about string functions

radio

Contains information about a form's radio button

checkbox

Contains information about a form's checkbox button

select

Represents a form's list as an array

button

Contains information about a form's button; it could represent a

 

form's reset, submit, or custom button

text, textarea

Contains information about a form's text box

location

Contains information about the current URL location

JavaScript Language Structure

Listing 18.2 shows an example of HTML code that includes a JavaScript function. The JavaScript code is identified by the <SCRIPT> tag. The code is embedded between the beginning and ending <SCRIPT> tags.

Listing 18.2. Basic structure of a JavaScript function.

<SCRIPT LANGUAGE="JavaScript">

<!--

function <function_name> {

...

}

// -->

</SCRIPT>

Listing 18.3 shows a JavaScript-based HelloWorld function.

Listing 18.3. JavaScript HelloWorld function.

<SCRIPT LANGUAGE="JavaScript">

<!--

function HelloWorld() {

alert("Hello World!");

}

// -->

</SCRIPT>

The LANGUAGE attribute indicates the scripting language that is used. The browser interprets the code accordingly. Microsoft Internet Explorer 3.0 can interpret both JavaScript and VBScript. Netscape Navigator and HotJava can interpret only JavaScript.

NOTE

Although currently only Microsoft Internet Explorer supports VBScript, other browsers are expected to include support for interpreting VBScript code.

JavaScript functions can be placed anywhere inside the HTML code, including the HEAD and BODY sections. It is recommended you place all your functions and procedures in one location, usually toward the end of the BODY section, before the </BODY> tag.

JavaScript Operators

JavaScript operators include arithmetic, comparison, logical, and bit operators. Table 18.2 shows the JavaScript arithmetic operators.

Table 18.2. JavaScript arithmetic operators.

Operator Meaning

+ Addition

- Subtraction/negation

* Multiplication

/ Division

++ Increment

--

Decrement

%

Modulus

Table 18.3 shows the JavaScript comparison operators.

Table 18.3. JavaScript comparison operators.

Operator

Meaning

!=

Non-equality

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

Table 18.4 shows the JavaScript logical operators.

 

Table 18.4. JavaScript logical operators.

Operator

Meaning

&&

Logical AND

||

Logical OR

!

Logical NOT

Table 18.5 shows the JavaScript bit operators.

 

Table 18.5. JavaScript bit operators.

Operator

Meaning

&

Bitwise AND

|

Bitwise OR

^

Bitwise XOR

A single = is the assignment operator. It is used to store a value into a variable.

JavaScript Flow of Control Statements

Table 18.6 shows the JavaScript flow of control statements.

Table 18.6. JavaScript flow of control statements.

Statement

Meaning

For ([initial_expression;][condition;]

Execute the code

[increment_expression])

within the loop for N

{

times where N is

statement 1

specified in the For

...

loop

statement N

 

}

 

For Each...Next

Execute the code

 

within the loop for

 

each item in the

 

specified collection

If (condition) {

If...Else statement

statement 1...

 

statement N}

 

[else {

 

statement 2}]

 

while (condition) {

Execute the code

statement 1

within the loop as long

...

as the specified

statement N

condition is true

}

 

VBScript Language Structure

VBScript is a lightweight portable subset of Visual Basic, the language, and Visual Basic for Applications, the scripting language used in Microsoft Excel and Word. It is a scripting language that can be used as part of your HTML code for designing and modifying Web pages. Similar to JavaScript, you can change the appearance and behavior of your Web pages dynamically using VBScript. You can process mouse events such as a mouse click or the mouse moving over a certain part of the Web page and initiate certain actions on such events. For instance, you can display different background bitmaps, depending on the day of the week. You can process form data when the user clicks the Submit button and alert the user of any invalid data. VBScript can also be used as part of other applications that use ActiveX controls, OLE Automation servers, and Java applets. As of this writing, VBScript is available only as part of Microsoft Internet Explorer 3.0.

If you are already familiar with Visual Basic, the programming language, you will be able to quickly and easily grasp VBScript. There are a few important differences, though. VBScript does not support strict data types. It supports only variants. It does not support file I/O. Nor does it include direct access to the underlying operating system.

How does VBScript compare with JavaScript? Well, it is directly comparable to JavaScript. In fact, VBScript is a competitor to JavaScript. Both languages have their advantages and disadvantages. Visual Basic has been around for quite some time. Java is relatively new. According to a recent ComputerWorld survey, there are approximately 3 million programmers who use Visual Basic as their primary programming language. The introduction of VBScript is clearly a welcome sign for these programmers. A lot of them would find it easier to use VBScript with their HTML code than to learn a new language, JavaScript. Neither JavaScript nor VBScript can produce standalone applets. However, they can be used to add intelligence and interactivity to HTML documents.

NOTE

If you are an experienced Visual Basic programmer you will find it easy to learn and understand the lightweight subset of Visual Basic, VBScript.

Presently, VBScript is available for Windows 95, Windows NT, Windows 3.1, and Power Macintosh platforms. UNIX