Lab 7
Page 3


Programming in Java


What is Java?

Sun Microsystems (the company that designed Java) describes Java as a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language. Fortunately for everybody's sake, we will only discuss two features of Java. Specifically, we will consider Java as an object-oriented, portable language. First, however, a few words about how programs go from the high-level programming language to the machine code your computer understands.


Translators

OK. You've written a program in a high-level langugage such as C or Java. The problem is, your CPU was designed to execute only its own native machine language instructions. So you need some way of converting your program into an equivalent sequence of machine language instructions. This is the job of a translator program.

High-level languages usually employ one of two types of translators: a compiler or an interpreter. A compiler is a translator that reads your high-level program and converts the entire thing into a working machine language program. An interpreter is a translator that converts and executes your program, one line at a time. That is, an interpreter will read one line of your program, convert it to machine intstructions, execute those, then convert the next line, execute that, and so on. (The translator for assembly language programs is called an assembler.)


Portability

A program is said to be portable if it can be made to run on many different kinds of computers. While a program in a high-level language can be compiled for different kinds of computers, the resulting machine language program can run on only one kind of computer. Most application programs that you use are in machine-language and are not portable. If you were to copy the word processor from your Intel PC to, say, a DEC Alpha workstation, it would not run there. Why? Because the same numbers that represent the machine code for a useful working program on your Pentium chip will represent a seemingly nonsensical "gibberish" program on the Alpha chip.

However, programs written in Java are portable. A Java applet will run equally well on your computer, on the computer down the hall, and on the Alpha workstation (we'll explain why in a moment). Portablity is good because the programmer can concentrate all effort on just a single version of the program. No time must be wasted rewriting the program so that it will work on each different kind of computer.

Because the Web contains many kinds of computers, you cannot assume that everyone is using the same kind that you are. Thus, if you want to write a program that can run Web-wide, it must be portable. This excludes compiled programs (those created by compiling a high-level language), because the compiler creates machine language, which we know is not portable.

The other possibility is to use interpreted programs. If you write your program in an interpreted language, then everyone can run it, as long as they have the interpreter for that language running on their own computer. On the other hand, interpreted programs tend to run very slowly in comparison to compiled programs, so an interpreted language is also not a perfect solution.

Java's answer to this dilemma is to be both compiled and interpreted. It does this in the following way:

Of course, because those real machine instructions are different on different kinds of computers, Sun (or some other company licensed by Sun) actually had to write a different version of the JVM for every kind of computer. In many cases, the JVM is built directly into a web-browser (e.g. Netscape 3.0).

Because the JVM interprets programs which are already in a relatively simple format (namely, Java virtual machine language), it can run much faster than would an interpreter designed to translate Java directly into machine instructions. Thus, with Java there is a gain in speed and portability over other interpreted langauges, at least theoretically.


Writing Java Code

Overview

Here we will provide a very brief overview of some of the commands and syntax available in Java. This is by no means a complete reference, however. There are many great web sites that contain the entire Java language specification--if you want more information than we provide here, please look to one of those sites.

Declaring Variables

A variable is simply a name that refers to a location in memory. Variables can be of many types which specify how the value stored in that memory location should be interpreted. A few possible types for Java variables are: int (integer), float (floating point number), char (single ASCII character), boolean (TRUE/FALSE value), and String (string of ASCII characters).

Before you can use a variable in a Java program, you must first declare its type. For example:

int age, height, weight;
String first_name, last_name;
char middle_initial;

Comments

Comments provide a means for adding explanatory text to your program code, making it more understandable to human observers. In Java, comments are indicated by // (double-slash). Everything on a line after the // will be ignored by the compiler.

Indentation and Space

"Proper" indentation is a programming practice that makes your code easier for other humans to read and follow. However, it has no effect whatsoever on how the compiler reads your program. Choose an indentation style that suits you, and stick with it.

Operators

Operators are special symbols that act upon the values or variables that precede or follow them (depends on the operator). Some of the important operators are the following:

Operator Description
=
Assigns value on right to variable on left (e.g. x=y+10;)
+,-,*,/,%
Arithmetic: add, subtract, multiply, divide (integer), remainder (ideal for Euclid's greatest-common-divisor algorithm)
+
Strings: concatenate left string with right string
<,<=,>,>=
Comparators: less than, less than or equals, greater than, greater than or equals
==,!=
More comparators: equals, doesn't equal
&&,||
Conditional AND (true if left and right both true) and conditional OR (true if either left or right is true)
++,--
Increment/decrement value by 1

Control Statements

Control statements--such as if, while, and for--dictate the flow of a program based upon the truth of some conditional test. Each of these statements are described below.

if

if (condition) action else other_action

If the condition evaluates to TRUE, then the action is taken, otherwise the other_action is taken. Note that the action and the other_action can be blocks of statements enclosed in { and }.

while

while (condition) action

As long as the condition evaluates to TRUE, then the action will be repeated. Note that the action can be a block of statements enclosed in { and }.

for

for (initialize; condition; increment) action

First, the expressions in the initialize section are evaluated. Then, dependent on the truth of the condition, the action and then increment sections are repeatedly executed, until the condition evaluates to FALSE. Note that the action can be a block of statements enclosed in { and }.

Semicolons and Braces

Java demands that every complete statement end with a ; (semicolon). Also, if you would like a group of statements to be used where the syntax calls for a single statement, you must enclose this group of statements within { and }. For example:
if (x==1) {
   foo = 10;          // These two statements comprise 
   y++;             // the "action" of the if.
}
else {
   foo = 20;          // And these three
   y--;             // comprise the "other_action"
   a = name.length; // of the if
}

Creating Objects

variable = new class(constructor arguments);
To create a new instance of a class (i.e. a new object), use the new keyword, as in this example:
Student s;           // first declare a variable of the class Student
...                  // (...other code in between...)
s = new Student;   // later, create an instance of the class, referred to by s
Constructor arguments may be used to give information such as the size of an object or initial values, depending on how the class is defined. For example, an object of class String (character strings) can be initialized:
String msg;           // first declare a variable of the class String
...                  // (...other code in between...)
msg = new String("hello");   // later, create a String object, referred to by msg
                            // and initialized to "hello"

Accessing Objects

Once you have created an object, you can view and manipulate its data only by invoking the object's methods. The syntax for invoking a method is:
object.method(arguments)
where object is the name of the object instance, method is the name of the method to invoke, and arguments is a comma-separated list of values to be passed to the method. For methods that do not take any arguments, the arguments list is left blank (although the parentheses are still kept).

As an example, let's suppose we have defined a Student class that contains only one piece of data, a string to store the student's name. Also, suppose this class has only one method, called setName, that lets you change the name stored in the string. The code below illustrates how one would create a new student object and invoke its setName method:

Student s;             // declare a variable s of type Student

s = new Student;       // make a new Student object
s.setName("Allison");  // set the name field of this student to Allison


PREVIOUS 1 | 2 | 3 | 4 | 5 | 6 | 7 NEXT