Variables
Home - About Us
Expressions More Selection

As mentioned in the Expressions section,  a declaration statement can be used to setup a chunk of memory to hold a value.  The declaration statement shown below creates an integer variable named age:

	int age;

This declaration statement does three things:

  1. Grabs four bytes of the computer's memory.
  2. Notes that that memory can only be used to hold integer (int) values.
  3. Gives that chunk of memory the name of age, so that it can be easily referenced later in the program.

The picture below shows four bytes of the computer's memory reserved for the variable age.

Instead of the redrawing the entire computer each time I want to visually represent the age variable, I'm going to reduce the complexity of my drawing of age to this simple box

You are supposed to visualize this simplified box as four bytes of memory inside the computer.

A value can be assigned to a variable via the assignment operator: =.  An assignment statement always take the value on the right hand side of the = operator and assigns that value to the memory location on the left hand hand side of the = operator.

After the completion of this assignment

	age = 37;

the visualization of the age variable changes to

An integer variable can only hold a single integer value.  If a new value is assigned to the age variable

	age = 90;

then the preceding value of 37 is replaced

Here is a sample program, with a visualization of memory after the instructions have been performed:

   public class DemoVars
   {
      public static void main (String [] args)
      {
	      int total = 50;
		  total = total + 6;
      }
   }

The initial value of total is 50. Taking a look at the second statement in the above program, remember that an assignment operator takes the value on the right and assigns it to the memory location on the left. The value on the right is calculuated first.  That value is the current content of total (which is 50) plus six for a value of 56.  The value of 56 is then assigned back into the total variable.

Example

Here is an example that uses several variables

int fruit = 0;
int apples = 3;
int pears = 5;
apples = apples + 4;
pears = pears + 10;
fruit = apples + pears;

With a final result of:

Increment and Decrement Operators

A common action in Java is to add one to variable.  For example, if an integer num has been declared and assigned a value

	int num;
	num = 50;

then the instruction

	num = num +  1;

adds one to num to increase its value to 51.

Another way of adding one is the unary increment operator: ++.  For example

	num++

increments the current contents of num by one.

There is also a unary decrement operator --, which subtracts one from its operand:

	num--;

For example, after the following instrucdtions have been performed
	int x = 30;
	int y = 5;
	
	x--;
	x--;
	
	y++;
	y++;
	y++;

The variable x contains the value 28 and y contains 8.

Some Shorthand Operators

A common abbreviation of an instruction such as this

	num = num + 3;

is to write it as

	num += 3;
Similary shorthand notations are allowed for *, /, -, and %, as shown in the following instructions:
	int sum = 10;
	sum *= 5;  // sum is now 50
	sum /= 2   // sum is now 25
	sum -= 5;  // sum is now 20
	sum %= 6;  // sum is now 2

Strings and Concatentation

Even though there are only eight built-in Java data types, there are an infinite number of abstract data types that can be defined by Java users.  An abstract data type is created by defining a Java class.  One abstract data type is the String class.  To create a String variable, use a declaration such as this:

	String name = "Joe";

The String "Joe" can be replaced by a new value, such as "Allison", via the assignment operator

	name = "Allison";

Even though the concept of addition does not apply to Strings, the Java language allows programmers to use the + operator to concatenate two Strings to make a new combined String:

	String both = "Bill" + "Clinton";

The both variable, above, contains the String "BillClinton".  There are several ways to add a blank between "Bill" and "Clinton".  One is to add in a separate String that contains a single blank character

	String both = "Bill" + " " + "Clinton";

Even when using Strings, the + operator still follows the normal arithmetic rules on associativity -- the leftmost + is performed first to yield

	"Bill " + "Clinton"
and then the remaining + is performed to get
	"Bill Clinton"

If an attempt is made to add an integer or double to a String, the int or double is first promoted to a String and then the concatenation takes place.  For example, in this expression

	"Age is: " + 33

the int 33 is first promoted to a String "33"

	"Age is: " + "33"

and then the concatenation takes place to yield the String

	"Age is: 33"

Since the promotion from int to String takes place one + operator at a time, and the + operator has a left-to-right associativity, you have to be careful, as some expressions will give unexpected results, such as

	"value is: " + 5 + 2

which does not yield "value is 7", as might be expected, but instead yields

	"value is: 52"

The more intuitive result of "value is: 7" can be accomplished by forcing the addition of the integers to happen first, via a pair of parenthesis

	"value is: " + (5 + 2)

The + operator is often used to concatenate values to Strings in println statements:

	int rate = 8;
	int hours = 40;
	int pay = rate * hours;
	System.out.println("Pay will be $" + pay);

The println will print the string "Pay will be $320" to the output console.

Identifiers

There are two issues to consider when choosing a name for a variable -- is it a legal name, and does it have good style?  A legal name is one which the compiler is able to successfully translate.  The Java rules for creating an identifier (e.g., a variable name), are that it:

  • can contain upper and lower case letters (a-z and A-Z),
  • can contain numeric digits (0-9)
  • can contain the special symbols of underscore ('_') and dollar sign ('$')
  • the first character of an identifier cannot be a digit
  • it cannot be a reserved word

Therefore, the following are valid identifiers

  • taxRate
  • tax4Me
  • TAX_ME
  • tax$toPay

and these are not valid

  • 4best  (cannot start with a digit)
  • three@front  (@ is not an allowed character)
  • tax  me (the blank between "tax" and "me" is not an allowed character -- an identifier is one continuous word)

Style is a separate issue.  Just because an identifier will compile successfully does not mean it is one that a Java programmer would find acceptable.  Java programmers, generally, prefer that variable names use all lower case letters (including the first character of the identifer) and except when starting an interal word (i.e., the first letter of an internal word is upper case).  Using digits is generally acceptable, but do not use the underscore or the dollar sign.  Therefore, the following all good identifiers, with respect to style, for variable names:

  • taxRate
  • taxes4December
  • doors
  • houseSalesBeforeSummer

These are generally not considered to be good style for variable names (or at least I do not consider them to be good style):

  • tax_rate
  • TaxRate
  • taxRATE
  • Doors
  • tax$s
  • house_sales_before_summer
  • _bread

The style for class names is the same as for variable names, except class names should always start with an uppercase letter.  Therefore, these are good style for class names:

  • Houses
  • FederalTaxes
  • Auto
  • FirTrees

and these are not good style for class names:

  • houses
  • federalTaxes
  • federalTAXES
  • Fir_Trees

Binary Numbers

A computer is just a machine, but it is a machine that keeps track of information, such as letters and numbers. Unfortunately, the computer does not have anything as fancy as a human brain, so keeping track of letters and numbers is a bit difficult. The computer records information in its memory using rows of bits.  A bit is something like a tiny light bulb which is either on or off.  In realitiy, a computer bit is a capacitor and a transistor working together -- the capacitor is either storing a small electric charge (i.e., is on) or is not storing a charge (off ).  The transistor helps the process of turning the capacitor on and off, and also is used to read the current state of the capacitor (i.e., it can check if the capacitor is on or off). 

A set of bits can have different patterns of on and off to represent to different values. A similar system that we see everyday is a traffic light. A traffic is a row of three light bulbs, and different on/off patterns have different values:

	on     
	off   means STOP
	off
	
	off
	on    means YIELD
	off
	
	off
	off   means GO
	on
On a computer the different on/off patterns indicate different numeric values. The computer puts the bits into small groups called bytes (a group of eight bits). Each group is given a different on/off pattern to represent a specific number. For example, if we look at a byte that has all of the bits turned off:
	off off off off off off off off   means  0
and if only the last transistor turned on
	off off off off off off off on   means  1
If the last two bits are turned on
	off off off off off off on on   means  3
When referring to the value of bits people typically write a 0 for off and a 1 for on. So the values shown above could be written as follows:
	0 0 0 0 0 0 0 0  means  0
and only the last bit on
	0 0 0 0 0 0 0 1  means  1
The last two bits on:
	0 0 0 0 0 0 1 1  means  3

If you use a certain set of on/off patterns for the bits then the bit patterns can represent numbers in base 2 (binary).  Humans typically write numbers using base 10 (decimal).  Each place, or digit, in a base 10 number has a given value.  For example, the number 3692 can be interpreted as follows:

	1000   100   10    1
	---------------------
	  3     6    9     2

The total value of 3692 is determined by mulitiplying each digit by its column value (i.e., 3 x 1000, and 6 x 100) then adding these results together (i.e., 3000 + 600 + 90 + 2 = 3692).  The same system is used for base 2 numbers, except the column values are based on the powers of (1, 2, 4, 8, 16, etc.) instead of powers of 10 (1, 10, 100, 1000, etc.).

The example below shows how to determine the value of the binary number 00010010.  The numbers above line indicate how much each column is worth -- that column value is multiplied into its corresponding binary digit.

	-128  64   32   16   8   4    2    1
	--------------------------------------
	  0    0   0    1    0   0    1    0
A '1' picks up, or is multiplied into, the value above it. A '0' is just zero. So in the example above there is a '1' at the 16 place and a '1' at the 2 place'. Add these together and you get the value 18, which is the value intended to be stored in the computer in this case (i.e., 1 x 16 + 1 x 2 = 18).. Therefore
	0 0 0 1 0 0 1 0  (in base 2) = 18 (in base 10)

Determine the decimal (base 10) values of the following binary (base 2) numbers. Write your answers on a scrap piece of paper.
  1. What is the value of binary number 0 0 0 0 0 0 1 1 in base 10?
  2. What is the value of binary number 0 0 0 1 1 0 0 1 in base 10?
  3. What is the value of binary number 0 0 0 0 0 0 0 0 in base 10?
  4. What is the value of binary number 0 0 1 0 0 0 0 0 in base 10?
  5. What is the value of binary number 0 0 0 0 1 1 0 0 in base 10?

You might have noticed that the left-most column is a negative 128.  This allows us to represent negative numbers.  For example, the binary number

	1 0 0 0 0 0 0 0

represents the decimal value -128, and the binary number

	1 0 0 0 0 0 1 1

represents -125 (-128 + 2 + 1).

Determine the decimal (base 10) values of the following binary (base 2) numbers. Write your answers on a scrap piece of paper.

  1. What is the value of binary number 1 0 0 0 0 1 0 0 in base 10?
  2. What is the value of binary number 1 0 0 0 0 0 1 0 in base 10?

Using the scheme described above:

  1. What is the smallest (most negative) value that you can store in 8 bits?
  2. What is the largest (biggest positive) value that you can store in 8 bits?

Here are the answers to the above questions.

 

Home - About Us
Copyright © 2006 by Kiowok, Ann Arbor, Michigan, USA