(syllabus and calendar)Ch. 1 Java Fundamentals |
Session 1Applications, Applets and Servlets Java has nothing to do with JavaScript Java class libraries - built-in core APIs OOP = encapsulation + polymorphism + inheritence Demonstration of a Java program PATH and CLASSPATH (often important for getting set up) |
Traditionally, software programs have been written in source code and then compiled into
machine code that talks directly to the operating system that drives the
microprocessor in the computer. This means that traditional programs depend on,
and are bound to, a particular type of hardware (the microprocessor), a
particular platform. Porting from one platform, or operating system, to other,
is traditionally time-consuming and prone to errors. The Java platform is a
virtual platform that mitigates this dependency by
providing a model in which software is written and compiled, and can then be
transmitted over a network and run anywhere by a fully compliant
virtual machine. Whereas it is
not practical for end-users of, say, a Windows machine, to add a Macintosh chip
and motherboard to their laptop, it is feasible for a Unix, Linux, Windows,
Macintosh, or even a hand-held personal assistant to install the application
that provides a Java virtual machine (JVM). Now the internet becomes a viable
distribution medium for programs that are intended to run on multiple platforms.
This model provides the additional benefit of heightened security, both because
programs can be verified by the client's virtual machine after they have been transmitted
over a network, and because the client's virtual machine can run programs in a secure
"sandbox" that prevents certain destructive behaviors.
Software programmers have embraced the Java platform because it reduces the cost
and time required to write and support software code. They are no longer
required to rewrite software to function on different computers with different
operating systems and microprocessors. Companies and organizations deploying
applications favor Java technology because it minimizes the cost of purchasing
or modifying different versions of software applications for the various types
of computers and servers within their networks.
The promise of Java: http://java.sun.com/docs/books/tutorial/getStarted/intro/changemylife.html
| Types of languages | ||||
| Object-oriented programming | Procedural | Web scripting | Page description | Data description |
| Java, C++, SmallTalk, Objective-C, C# | C, Basic, Fortran, Cobol, Lisp, Perl | JavaScript, VBScript | HTML | XML |
The runtime environment is for users who only need to run existing Java bytecode and do not write the code. http://java.sun.com/j2se/1.4/ The Java Runtime Environment consists of the Java virtual machine, the Java platform core classes, and supporting files. It is the runtime part of the Java 2 SDK, but without the development tools such as compilers and debuggers. (The JRE download is only 8 MB, compared to 38 MB for the SKD download.) The installer for certain programs might install the runtime environment so that end users can run the application.
Java programming is the process of creating:
Sun Microsystems likes to think of the Java platform as a target for software development, much as traditionally software developers targeted an operating-system or processor-based platform such as MacOS/Motorola, Windows/Intel, or Sun/Sparc.
To develop code for the Java platform, the software developer uses:
Note: some Java developers might use the following:
Some people say JDK (Java Development Kit), and this is the same as the Java
SDK (Software Development Kit).
However, the JRE (Java Runtime Environment) is a subset of the SDK for
running Java programs that does NOT include development tools.
To run your code, you and whoever uses your code will need:
An application is software that runs on top of the operating system, has a specific purpose, and usually allows an end-user to interact. An example of an application is Microsoft Word. On the other hand, the software that runs your printer (a "driver") is something for the operating system or an application, rather than for the human user.
Java introduced the concept of applets, which are applications that can run inside of a web browser on the client computer. A web browser is an application.
An applet is a "safe" quasi-application that can only run inside of another, very specific application. Some of the key restrictions on an applet
These restrictions are meant to give web surfers confidence to download applets from the web, even if the user does not know the company that created the applet
If an applet provider registers a specific applet with a registration company, the "signed applet", if you accept it, can have access to your file system and the native operating system. This is called a "signed applet". http://mindprod.com/jgloss/signedapplets.html#SIGNEDAPPLETS
Note: A Java application, like any application, does have access to your file system.
http://java.sun.com/products/plugin/index-1.4.html
The Java Plug-in allows you to run applets using Sun's Java 2 Runtime
Environment, Standard Edition (JRE) instead of the web browser's default virtual
machine. Sun's JRE provides a Java CompatibleTM
environment for today's widely adopted web browsers. That means consistency and
reliability when running applets.
The Plug-in can give the browser support for Swing. Swing is part of the Java 2 Foundation Class library that extends the Java 1 Advanced Windowing Toolkit (AWT) to provide new GUI components and features, better event handling, and selectable look and feel]
Unless Internet Explorer is used in conjunction with the Java 1.4 plug in, your users are limited to the functionality of Java 1.1 http://mindprod.com/jgloss/ie.html
http://java.sun.com/products/servlet/index.html
JavaTM Servlet technology provides
web developers with a simple, consistent mechanism for extending the
functionality of a web server and for accessing existing business systems to
give them a web interface. A servlet can almost be thought of as an applet that
runs on the server side -- without a face. Java servlets have made many web
applications possible.
JavaScript is a marketing misnomer because the JavaScript scripting language has nothing to do with the Java programming language. In 1995, Netscape wanted to capitalize on the name of Java so as to appear technologically advanced. Sun wanted support for Java to be built in to Netscape Navigator, which was the most popular browser at the time.
In 1996, Microsoft copied JavaScript, changed the name to JScript to avoid a lawsuit, and gave Microsoft Internet Explorer built-in support of JScript.
JavaScript is a limited tool to enhance a subset of the capabilities of an HTML browser. JavaScript can be used to open a new HTML browser window, to validate the data types of entries in an HTML form (credit card numbers should have no letters), and to cause a browser image to change when the mouse hovers over an existing image.
For performance, JavaScript runs on the web client, but web client computers suffer from vulnerability to security weaknesses inherent in JavaScript, including internet banking theft. http://en.wikipedia.org/wiki/JavaScript#Security
A computer platform is the combination of the operating system and the central processing unit (CPU).
Examples of operating systems include
Examples of CPUs include
A standard, compiled application runs machine code that is specific for a platform. Machine code is the raw zeros and ones that a computer "chip" understands. If you want your UNIX application to run on Windows, for example, you must "port" the code and recompile it using a compiler that produces machine code that is "native" to the target CPU. Porting costs developer time and some platforms have different kinds of data types or a different number of bytes for the same data type.

Java code is different from standard, compiled code. You compile your Java source code into a special language, "bytecode", that a special application, the Java virtual machine (JVM), interprets. With one binary code (bytecode) for one virtual machine for all the operating systems, there is no need for porting. Each hardware platform, however, still needs an interpreter to convert the bytecode into native machine code.
The Java interpreter (java) is different from the "HotSpot" just-in-time (JIT) compiler. The interpreter interprets bytecode and makes application programming interface (API) calls into the native operating system, for example, calls to Win32API. The JIT compiler can improve performance with optimization capabilities that allow it to compile into native machine code parts that are most heavily used.
The JVM is an application that emulates a computer. It translates Java bytecode into native machine code.
There is a JVM for Mac OS, UNIX, Linux, and Windows. This means that the same source code should be valid for multiple platforms. You do not need to "port" the application to another platform. It should be "write once, run anywhere", assuming there is a JVM for that platform.
There are even JVMs for smaller platforms, such as the PalmOS that runs on the PalmPilot.
| Pro | Con |
| Less likely to create careless bugs (memory leaks, pointer errors) | performance is slow because of CPU-intensive interpretation or compilation of byte code into machine code |
| Relatively platform independent: "write once, run anywhere", which is particularly valuable if the server could be Unix, Linux, or Windows, and you don't which it will be | vision is not fully realized write once, debug everywhere |
| strict object-oriented model; cannot mix with procedural code, so coding is more straightforward | can use more CPU and memory (C++ can be optimized with lower-level code) |
| Dynamic linking: supports introducing new objects at runtime without recompiling everything [RMI (remote method invocation)] | slower because of look up; mitigate with JIT compilation |
For more on static versus dynamic linking: http://www.cpp.atfreeweb.com/StaticVersusDynamic.html
From Sun's point of view, Java 1.4.1 is part of Sun's J2EE platform. C# is a Microsoft programming language that closely resembles Java. C# is for use in Microsoft's .NET platform, which relies on libraries of the Microsoft Windows operating system. Insofar as .NET has an intermediate language (IL) and a common language runtime, there is a something analogous to a JVM-like portability, but only within the Microsoft family of programming languages, such as Visual Basic, J# (Microsoft's version of Java), and C#, and only for use on Microsoft operating systems. Whereas the Java platform offers portability across operating systems, the .NET platform is an integration within Microsoft's "family" of languages. From Microsoft's point of view, .NET frees you from being confined to any one language, such as Java, and allows you to use whatever Microsoft language you freely choose. For example, VB.NET syntax might be most convenient for a developer of end-user applications and C# syntax might be a bit more familiar for the C++ developer working with pointers. However, all of the .NET languages actually have the same capabilities.
.NET source code in any .NET language >> IL (analogous to bytecode) >> runtime interpretation to native code
For details, see http://genamics.com/developer/csharp_comparative.htm.
The virtues of Java (as in theory of C#):
http://java.sun.com/docs/overviews/java/java-overview-1.html :
Simple

Sun defines three (3) Java platforms at http://java.sun.com/java2/whatis/:
http://java.sun.com/j2se/1.3/
The JavaTM 2 Platform, Standard Edition
(J2SETM) has revolutionized computing with the
introduction of a stable, secure and feature-complete development and deployment
environment designed from the ground up for the Web. It provides cross-platform
compatibility, safe network delivery, and smartcard to supercomputer
scalability. It provides software developers with a platform for rapid
application development, making it possible to deliver products to market in
Internet time. It defies traditional software development and deployment models
by delivering on the promise of cross-platform compatibility.

The Software Development Kit (SDK) is much more than a language. There are many
convenient implementations you can use and customize in your applications.
The code provided for your applications is the application programming
interface.
(You can think of APIs as "hooks" you can grab and use, without having to know
the deepest level of Java, which is actually C++.)
The core APIs save you the work of "reinventing the wheel" and allow you to
program at a higher level.
For example,
In the 1.4 J2SE, the JRE and the SDK include new core
application programming interfaces (APIs), such as XML
and Logging:
http://java.sun.com/j2se/1.4/docs/relnotes/features.html
http://java.sun.com/j2se/1.5.0/docs/index.html is for the 1.5 version.

http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
The set of new features in the latest release of Java provide some conveniences.
Perhaps they are an attempt to make Java easier to use for people who write code
for Microsoft's .NET platform.
An alterative to casting various objects to type Object. This alterative provides type safety. To enable this feature, the concept of a Collection has been expanded to support type checking.
A convention way to iterate over all the items in a collection, such as an
array. [pp. 172-178]
for(int x: nums) sum += x;
A convention way to work with a collection of constant values that require identifiers. This is an alternative to final variables such the set of constants are their own data type. The java.lang package now contains the Enum class.
A convenience that automates the process of wrapping a primitive into its
corresponding object type.
Integer myValue = 100; // wraps the primitive into
its corresponding object type
int myInt = myValue; // automatically unboxes the object to its primitive
variable length arguments to a method
Allows you to provide annotations for use in build management, such as marking a particular method as deprecated. Deprecated means outdated, and might be removed from a future release.
What is a parser? The part of javac that prepares your source code for compilation into bytecode, and that allows the debugger to alert you of possible problems.
|
When you invoke the javac compiler, it parses the tokens in your source code. The parser ignores the contents of comments as well as white space. Therefore, the following are the same:
When you name identifiers (variables, methods, classes), the characters must be contiguous (no spaces), cannot start with a numeral, and cannot include operators.
| CHARACTER | NAME | USE |
; |
semicolon | to end a statement |
. |
dot operator | to separate an object from one of its members (methods and properties) for the syntax object.member |
( ) |
parenthesis | to contain a list of parameters (or arguments) for a method; to contain the condition in a control statement |
{ } |
curly braces | to define a block of code |
[ ] |
brackets | to declare an array and to contain assignments to an array |
You cannot use the following as identifiers in your code.
true, false, and null are not
keywords but they are reserved words.http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
true |
false |
null |
|
abstract |
double |
int |
strictfp ** |
boolean |
else |
interface |
super |
break |
extends |
long |
switch |
byte |
final |
native |
synchronized |
case |
finally |
new |
this |
catch |
float |
package |
throw |
char |
for |
private |
throws |
class |
goto * |
protected |
transient |
const * |
if |
public |
try |
continue |
implements |
return |
void |
default |
import |
short |
volatile |
do |
instanceof |
static |
while |
When you use any language, whether it is a computer language or a human language, you have to follow the rules. The term "syntax" refers to the rules of word order and word combination. Some languages, like French, have a flexible syntax that lets you say "the chocolate good" as well as "the good chocolate". Other language are more rigid about word order. Java syntax is more rigid than, say, Perl syntax.
For example, Java has certain "reserved words" that you use according to Java's syntax and semantics. The Hello World application consists almost exclusively of reserved words or predefined words (in bold):
public class HelloWorld
{
public static void main (String[] args)
{
System.out.println("Hello World");
}
}
The only words that are not reserved words or predefined words are the three variables:
Just as human languages have punctuation in addition to words, so Java has special symbols, such as the curly braces { }, parentheses ( ), the brackets [], the comma separator , the wildcard asterisk *, quotation marks " ", the forward slash /, the backslash \, the dot . and the semicolon ; that completes a statement.
The Java software development kit comes with many built-in methods. This Java environment includes these methods to support major types of functionality, such as security, XML, networking, and input and output. Having a rich set of pre-built methods and properties saves you time. Here's an example.
/* This program uses API introduced in 1.1.
It tells you the language version of your Java.
In my case, in United States English: en_US */
public class CurrentLanguage {
public static void main(String[] args) {
System.out.println(java.util.Locale.getDefault());
}
}
Earlier, we saw that the String object has a method,
length(), for getting the length (number of characters) in the string.
An array has a property, length, that represents
the numbers of elements in the array.
The Java platform offers predefined formatting for numbers:
http://java.sun.com/docs/books/tutorial/java/data/numberFormat.htm
One student used the parseInt method of the Integer class to convert the strings of args[] into integers.
This is called conversion or type conversion. See Type Conversion.
Let's now take a tour of the API documentation: http://java.sun.com/javase/6/docs/api/
The Java platform specification lists the functionality that is available to a programmer out-of-the-box, without having to design, write, and compile low-level code.
Do not confuse the general concept of "interface" (a kind of abstract class) with the specific application programming interfaces (APIs) that are packaged with the SDK.
Core APIs are class and interfaces that are an integral part of (hence "core") the Java platform. We will look at the API documentation, and you will use some of the core APIs in your code so that you do not have to write everything from scratch.
In Week 4, we will see how creating a class allows us to encapsulate logic where it belongs.
In Week 6, how a method or constructor can be overloaded to perform its task differently in different situations. Each version of the method or constructor is a form, and Java supports many forms, which in Greek is polymorphism.
In Week 7, we will take advantage of features of inheritence to make specialized objects and maximize the reuse of existing code.
We could follow along this set of demonstration programs, which introduces concepts from Chapter 2 (data types) and Chapter 3 (Program Control Statements):
http://www.herbschildt.com/getting_started_with_Java.htm
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}Explanation of each token for the parser to parse in this application:
See also Lecture 2 on language tokens and parsing.
If there is no class that matches your classfile
name, you get an exception.
D:\java\teachjava\spring2003\session1>java
BadName
Exception in thread "main" java.lang.NoClassDefFoundError: BadName
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
Enclose multi-line comments inside /* */
Put single-line comments after //
//This is a wordy Java program.
//Call this file "Wordy.java".
class Wordy {
// Your program begins with a call to main().
public static void main(String args[]) {
int year = 2003;
System.out.println("This is a wordy Java program.");
System.out.println("This program uses the following:");
System.out.println("public static void main(String args[]) {");
System.out.println("The keyword public means this class is available for calls from outside the class.");
System.out.println("The keyword static means no class is initiated,"
+ "\nwhich is good because I do not have a class to initiate.");
System.out.println("The keyword void means this class does not return a value.");
System.out.println("The keyword String means that args[] is of type String.");
System.out.println("The variable name args[] refers to an array"
+ "\nbecause some programs take command line arguments.");
System.out.println("The print method prints to the screen without a new line.");
System.out.print("So the year value will appear on THIS line: ");
System.out.print(year);
}
}To assign a value to a variable, use the assignment (=) operator, which looks an equals sign.
class Assignment {
public static void main(String args[]) {
int x, y; // variable declarations
x = 100; // this assigns x the value 100
y = 10;
System.out.println("The value of x is: " + x);
System.out.println("The value of y is: " + y);
System.out.println("The product of x and y is: " + x*y);
System.out.println("The dividend of x / y is: " + x/y);
}
}TIP: Do not confuse assignment x = 4; with testing for true if x == 4;
Can you find the bug?
class HelloWorldApp2 {
public static void main(String[] args) {
System.out.println("Hello World!); //Display the string.
}
}D:\java\124115\sessions\demos\2\HelloWorldApp2.java:3: unclosed string literal

We will explore methods more in Week 4 of the course. This is just a preview.

Let's see a different application that puts the array of command-line strings into action:

The output is:
args[0]: sky args[1]: is args[2]: blue args[3]: 4 args[4]: you In this application, whatever the user types after invoking java with the application identifier is stored into the array of command line arguments. The for loop processes the array of command-line arguments.
String[] args
To make clear why the main method takes a parameter of type String array, let us make use of the string array.
It is best to write String[] args, but String args also works.


For consistency and simplicity, the string array is usually named args, but it is not a keyword or a reserved word, so its name (or identifier) can be something different.
Here's the same thing, but with a for loop to process multiple command-line arguments.

This source code must be in a file named CommandLine.java because the compiler expects the class identifier to indicate the class with the main method, that is, with the point of entry for execution.
Now, let's try to compile and run the program.

At the command line, I types a list of strings that the program stored in an array named applesauce.
What is an array? An ordered collection in which each item can be referred to by an index.
For example, an array of freeway lanes begins with the #1 lane. Here is a
northbound array and a southbound array. We might think of the number of these
lanes as the width of the freeway, and say it is 5-lanes wide, but in Java, we
consider the number of elements as the length.

In a redundant array of independent disks, a RAID array of hard disks, we have a 1-based array, with the lowest index
value being 1.
Each item in the array is of the same type (hard disk) and each item can store a
different value (different data).

Should it be possible to "populate" this array of hard disks in various
manners?
For example, can I have an array of hard disks in which Bay 5 is empty?
Can an entire array be empty of hard disks (or an array of freeway lanes be
empty of automobiles) and yet still exist an array?
In Java, arrays are 0-based, that is, they begin with zero instead of one
because binary counting begins with 0.
What is the capacity (or length) of the command-line String array?
A String is implemented as an array of characters (chars). An empty String is
a String without any chars.
In CommandLine.java, can I have an empty string
for one of my elements?

Now, let's run a program that does some arithmetic.

Finally, let's do arithmetic with input from the command line:

Note that this requires converting the command-line Strings into numbers.
Like other programming languages, you compile your Java source code (in a
text file) by invoking a compiler that outputs compiled code.
In this case, the compiled code is called "bytecode", which is in a .class file.
You can install the same .class file on multiple operating systems.
To enable platform independence, the Java platform inserts "interpretation"
between the compiled code (.class file of bytecode) and the operating system's
native machine code.
The Java interpreter, named java, converts compiled "bytecode" into machine
code.
The Java interpreter executes bytecode within the Java virtual machine, a sort of virtual computer inside the computer.

Or, if you prefer to visualize the sequence as numbered steps:
| STEP | DESCRIPTION | OUTPUT | NOTES |
| 1 | Write and save the source code file, which is a text file named after the class, such as MyClass.java | .java | |
| 2 | Invoke the Java compiler, javac, and specify the .java file
to compile: javac MyClass.java |
||
| 3 | The compiler outputs a .class file of bytecode, such as MyClass.class | .class | Look in your directory for this |
| 4 | Invoke the Java bytecode interpreter,
java, and specify the .class
file to interpret: java MyClass |
||
| 5 | Java Virtual Machine interprets the bytecode and outputs native code for the platform (Windows, UNIX, or Macintosh) | ||
| 6 | Operating system runs the native code | ||
| 7 | runtime memory management: The JVM periodically checks for unreferenced code (garbage collection) to free memory for reuse | In C/C++, this logic must be built into the code |
When you download the Java development kit at http://java.sun.com/javase/downloads/index.jsp, write down the drive and path in which the installer installs the Java development kit (JDK), so that you can verify the installation and, if necessary, configure Java so that the following are available from the command line of a console window:
The PATH system environment variable should point to the directory that has the java compiler (javac.exe), which is located in the the "bin" subdirectory of the installation directory for the JDK version.

For example, before the latest update became available, I went to my Windows Control Panel >
System > Advanced > Environment Variables
and edited the path by adding a new entry:
;D:\java5\jdk1.5_01\bin

You will probably have a slightly different version number.
The CLASSPATH variable is what the Java interpreter looks for to run a Java
program, the bytecode in a .class
file.
I want Java to be able to run whatever .class file I have in my current
directory.
Therefore, I also created a new user variable, CLASSPATH, and included:
.;D:\java5\jdk1.5.0_01;D:\java5\jdk1.5.0_01\lib\tools.jar

Then I logged out (or rebooted), so the changes would take effect.
http://www.cs.ucsb.edu/~teliot/Path_and_Classpath.htm
Setting the PATH and CLASSPATH on Windows XP
For VERSION 1.5.0 of Java
These
directions also appear in your book
in the section "Before you Begin"
NOTE: If a command is given in quotes for you to type, DO NOT TYPE THE QUOTES
1. Click on START (lower left)
2. Under "Settings" click on "Control Panel"
3. Switch to "classic view" (upper left) -- not "category view"
4. Click on the "System" icon.
5. Click on the "Advanced" tab.
6. Click on the "Environment Variables" button (bottom).
7.
Highlight "PATH" (in the top window "User" not "System") and
click the "edit" button.
(Do not edit the "SYSTEM VARIABLES" because of the risk for the
operating system.)
8. Edit the "PATH" so it begins C:\Program Files\Java\jdk1.5.0\bin; (note: if you install Java into a different directory, you may need to change the directory from that listed above)
9.
For example, the full "PATH" on my computer is:
C:\Program Files\Java\jdk1.5.0\bin;C:\Program
Files\SSH Communications Security\SSH Secure Shell
10. After you have finished editing the PATH, click "OK". You are done setting your PATH. Now you have to create a new variable, called your CLASSPATH.
11. Click on the "NEW" button below the top window.
12. Under 'variable name' type CLASSPATH
13. Under 'variable value' type . (yes, type a single period).
14. Click OK.
15. EXIT the control panel.
16. Restart your computer.
17. Test your installation by opening up a DOS window and verifying that both the commands "java" and "javac" are recognized.
Troubleshooting tips at http://java.sun.com/docs/books/tutorial/getStarted/problems/index.html
Be sure to read the installation instructions, including the section about updating the PATH variable:
If you have problems, see Sun's troubleshooting guide: http://java.sun.com/docs/books/tutorial/getStarted/problems/index.html