Lab 7
Page 2


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. In this lab, we will only discuss Java's portability. 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 Sun 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 Sun 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 Sun 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).

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. Comments are used to make the code more readable for other people that may have to work on it, or to remind you of what you were thinking when you did a particular line of code. In Java comments start with //(double-slash) and go until the end of a line or are inside a /* ... */ pair. Everything on a line after a // 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)
  {
    body
  }
As long as the condition evaluates to TRUE, then the body will be repeated. The body consists of one or more actions.

for

for (initialization; condition; increment)
  {
    body
  }
First, the expressions in the initialize section are evaluated. Then, dependent on the truth of the condition, the body and then increment sections are repeatedly executed, until the condition evaluates to FALSE. Note that the body is one or more actions.

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
}

Arrays

In Java, when an argument of a function is an array, it is declared as something like int a[] (which would make a an array of integer numbers). To refer to the first element in the array, you write a[0]; so to set the first element of the array a[] to have the integer value 9, you would say a[0] = 9. The nth element is accessed as a[n-1] because the counting starts at 0.

In Java, not only can you reference an item in an array, you can also determine the length of an array through its length field. For example, the following two lines of code print out the last item in the array named list[]. (Again, since the first item in the array has an index of 0, the last element in the array has an index one less than the array's length).

        int list[];
        ....
        last_index = list.length - 1;
        System.out.println (list[last_index]);  //"System.out.println" is the printing command

The for loop in Java is very useful when writing programs that use arrays. Using a for loop, one can step through each item of an array in order. The Java for the pseudocode ``for i=0 to (a.length-1)'' is for (i=0; i < a.length; i++). For example, a loop that prints out each element of an array called a would look like this:

int a[];
int i;
....
for (i = 0; i < a.length; i++)
  {
    System.out.println(a[i]);
  }


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