Sunday, December 9, 2007

Data,Operations and Methods

Data Types

Imagine what would happen if SimCom accidentally treated bytes of data as if they were instructions, or instructions as if they were data. In the first case, the virtual machine would execute a random series of opcodes, producing nothing of value. In the second case, instructions would likely be modified (added to or subtracted from one another), again producing nothing of value.

The point is that SimCom uses memory for two different purposes, instructions and data, and each memory type must be treated appropriately. There are no facilities built into SimCom to guarantee appropriate treatment. You just have to be a careful programmer.

This distinction between memory uses is also found in Java and all other high-level languages. Fortunately, Java makes it impossible to execute data or do arithmetic on opcodes.

SimCom has no facilities for dealing with fractions, characters, or very large numbers, and negative numbers are mysterious. Java supports all these different characteristics of numbers. It does this by providing different data types. For now, you can think of a data type as a way of using memory to represent data. SimCom uses an eight-bit base-2 representation. Java provides several base-2 representations: two representations for numbers that might contain fractions, one for characters, and one for logical (true/false) values.

Processing a Java data type as if it were a different type would produce worthless results. Java protects you from this kind of problem by requiring you to declare all data types; the compiler enforces the integrity of your declarations. Of course, this will make much more sense later in this chapter, after we discuss declarations. Right now, let's look at Java's data types. Later on, you'll see how they're used.

Integer Data Types


Name

Size

Minimum Value

Maximum Value

byte

8 bits

-128

127

short

16 bits

-32768

32767

int

32 bits

-2147483648

2147483647

long

64 bits

-9223372036854775808

9223372036854775807


Floating-Point Data Types


Name

Size

Minimum Value

Maximum Value

Smallest-Magnitude Positive Value

float

32 bits

-3.4 x 1038

3.4 x 1038

1.4 x 10-45

double

64 bits

-1.8 x 10308

1.8 x 10308

4.9 x 10-324


Declaring and Assigning

In a sense, computer programming is the art of assigning the right value to the right data at the right time. In Java, as in many other languages, you have to declare your data before you use it. Declaring means telling the compiler the types of data you will be using. In this section you will see how to declare and assign data, and will look at your first complete Java program.

When you programmed SimCom, you had to specify the address of each data operand. That meant you had to remember what you were using the different memory bytes for. For example, the Times 5 program used byte #29 as a loop counter and byte #30 for storing the result. Yet, when you look at the program for the first time, it's very difficult to tell what's going on.

In Java, you never have to remember which memory location is being used for which purpose. In fact, there is no way to even know which memory location is being used for which purpose. You pick a name for each memory location you want to use, and you refer to memory locations by name rather by address. The compiler assigns the addresses. All you have to do is tell the compiler the names you will be using, and the data type associated with each name.

For example, if you wanted to use a byte as a loop counter, it would be reasonable to choose the name loopCounter. Then you would declare as follows:

byte loopCounter;

A piece of memory that is declared and named in this way is known as a variable, so we will use that term from here on.

A declaration has three parts: a data type, a name, and a semicolon.

The data type (for now) is one of the eight primitive types: byte, short, int, long, float, double, char, and boolean. Later we will introduce some other types.

The name has to begin with a letter, an underline (_), or a dollar sign ($). The rest of the name can consist of letters, underlines, dollar signs, or digits. It is good programming practice to use variable names that begin with lowercase letters. If the name consists of more than one word, the second word and all subsequent words begin with uppercase letters. This is what we have done with loopCounter. Later in this book, you will see that there are other entities besides variables for which you will assign names (including classes and interfaces). These entities use different naming conventions. Following the conventions helps make source code easy to read.

The semicolon is a vital part of a declaration. A declaration is a kind of statement. A statement is a single instruction. All statements must end with a semicolon. Otherwise, the compilation will fail and the compiler will print out an error message with the line number where it ran into trouble.

Be aware that it is inherently impossible to create a compiler that produces consistently helpful error messages. Imagine someone running along a rough cobblestone road. If his foot slips on a stone, he might stagger for a few steps before falling. Similarly, if the compiler slips on an ungrammatical line, it might stagger over a few more lines before crashing and printing a message.

For the sake of convenience, you can declare multiple variables in a single statement, as long as the variables are all of the same type. So the following:

double mass, velocity, energy;

is equivalent to the following:

double mass;
double velocity;
double energy;

After you declare a variable, you can assign values to it. The following two lines declare and assign a variable called velocity:

double velocity;
velocity = 123.456;

Notice that the assignment statement, like the declaration statement, ends with a semicolon. An assignment statement has the form variable = value semicolon. (In the next chapter, you will see how the value can be a complicated mathematical formula. For now, the value will be a simple literal number.) Be aware that the equal sign is just a symbol, and its meaning is not exactly the same as its meaning in a mathematical context. In geometry, when we say Area = πr2, the equal sign means "is, always has been, and always will be." In Java, the

equal sign means "store the value to the right of the equal sign in the variable to the left of the equal sign."

When you assign to a char variable, the easiest approach is to enclose the value in single quotes, like this:

char ch;
c = 'w';

After execution, the variable ch contains the Unicode representation for the letter w. The single quotes can also contain special codes, called escape codes, that encode special characters. The most useful of these are

  • '\n' – Newline

  • '\t' – Tab


Arithmetic Operations

Java's arithmetic operations fall into two categories: basic arithmetic (addition, subtraction, multiplication, and division), and some more exotic operations such as modulo and shifting. We will begin by looking at the simple operations

Boolean Operations

So far, all the operations we have looked at have dealt with numbers. Now we turn our attention to operations that work on boolean data. Some of these operations share symbols with similar numeric operations (|, for example). However, the boolean versions are essentially different from their numeric counterparts.

Most of Java's boolean operations are binary, and both operands must be of boolean type.

Compound Assignment

Operator

Example

Equivalent

+=

x += 5;

x = x+5;

-=

x -= 5;

x = x-5;

*=

x *= 5;

x = x*5;

/=

x /= 5;

x = x/5;

%=

x %= 5;

x = x%5;

<<=

x <<= 5;

x = x<<5;

>>=

x >>= 5;

x = x>>5;

>>>=

x >>>=5;

x = x>>>5;

&=

b &= false;

b = b&false;

|=

b |= false;

b = b|false

^=

b ^= false;

b = b^false;

Compound assignments provide no new functionality. They just provide a convenient way to abbreviate.


Method Structure

The easiest way to introduce methods is with an example. Suppose you want to print out the fifth powers of the numbers 5 through 9. The following code, which doesn't use methods, does the job in a clumsy, inelegant way:

 1. public class NoMethods
2. {
3. public static void main(String[] args)
4. {
5. int n = 5;
6. int n5th = n*n*n*n*n;
7. System.out.println(n + " >=> " + n5th);
8. n = 6;
9. n5th = n*n*n*n*n;
10. System.out.println(n + " >=> " + n5th);
11. n = 7;
12. n5th = n*n*n*n*n;
13. System.out.println(n + " >=> " + n5th);
14. n = 8;
15. n5th = n*n*n*n*n;
16. System.out.println(n + " >=> " + n5th);
17. n = 9;
18. n5th = n*n*n*n*n;
19. System.out.println(n + " >=> " + n5th);
20. }
21. }

The application's output is

5 >=> 3125
6 >=> 7776
7 >=> 16807
8 >=> 32768

Scope

When you write a method declaration, you can choose almost any argument names you like. Of course, the names have to be legal (beginning with a letter, underscore, or dollar sign, and continuing with the same plus digits). Moreover, the name should be indicative of the argument's meaning. But beyond these considerations, you have complete latitude. In particular, you are allowed to reuse a variable name that has been used elsewhere in your program.



9 >=> 59049

No comments: