There was an error in this gadget

Monday, June 30, 2008

Primitive Variables: Sticks and Stones

In Java there are two types of variables. The simpler type are called "primitive" variables. This makes it sound like you'd only want to use them in programs for, say, starting fires or skinning cave bears. They're actually used in almost every program, and are very powerful.

There are eight types of primitive variable, each one holds a different kind of information. The types are:

boolean--holds a true or false value.
byte--holds an integer value from -128 to 127.
short--holds an integer value from -32768 to 32767.
int--holds an integer value from about -2 billion to 2 billion.
long--holds integer values too big for int.
float--holds a normal-precsion floating point number.
double--holds a high-precision floating point number.
char--holds one character (one letter or digit or punctuation symbol.

Two Steps to Making A Variable



There are two parts to creating any type of variable; declaration and initialization. In declaration you're giving the variable a name, and telling Java what type of variable it is:

int bugs;

In this statement, we've created a variable named "bugs" and told Java that it's an int (normal integer) variable. The name can be whatever you want it to be so long as it's not one of Java's keywords. You can look up Java's keywords in the Java Language Manual available online at Oracle's Java reference site.

A variable is initialized by giving it some value. In the case of a primitive variable, it's simple:

bugs=0;

You can get away without initializing primitive variables in your program, but it's a bad practice. By putting a specific value in the variable in your program, you know what's in your variable before you start using it.

The declaration and initialization can be combined into one statement, and most programmers do this most of the time:

int spiders=0;

You can also declare multiple variables in one statement by putting the declarations (and initializations) in a comma-separated list:

int frogs=0, salamanders=100, newts=3;

You can add linebreaks and whitespace to make longer lists more readable:

char
cow='c',
horse='h',
pig='p',
duck='d',
goose='g',
snake='s';

Many methods can work with primitive types as arguments. For example, println() can have any of the primitive types in it, and it will print them out appropriately:

System.out.println(cow);

Prints:

c

System.out.println(salamanders);

Prints:

100

You can define new colors for graphics in the color class using int variables:

Color amphibianColor = new Color(frog, salamander, newt);

or float variables:

float red=0.95, green=0.98, blue=0.0;
Color lightAmber = new Color(red, green, blue);


(These Color statements are a preview of the declaration and initialization of the other type of variable, reference variables.)
StumbleUpon