prev | TOC | next

Basics of the Java Language

files: AddEmUp.java (help)


We're now ready to dig deeper into the basics of the Java language.  This lesson is long and full of details.  You probably won't be able to absorb it all in one reading.  You will need to refer back to it again and again as you start programming.

To learn more about the language we'll look at a simple program.  Even a small program such as the one below uses many of the language features provided by Java such as:

  • variables
  • data types
  • operators
  • expressions, statements and blocks of code
  • control flow statements

1.   /**
2.    *  This simple program will add the numbers between 1 and 10 and
3.    *  print the result on the console.
4.    */
5.  
6.   import com.otherwise.jurtle.*;
7.  
8.   public class AddEmUp extends Turtle
9.   {
10.      int total = 0;
11.  
12.      public void runTurtle()
13.      {
14.          addUpTo( 10 );
15.      }
16. 
17.      private void addUpTo( int upperLimit )
18.      {
19.          int number = 1;
20.        
21.          while (number <= upperLimit)
22.          {
23.              total = total + number;
24.              number = number + 1;
25.          }
26.          System.out.println( "Total of 1 to " + upperLimit + " is: " + total );
27.      }
28. 
29.  }

Variables

Variables can be thought of as cubbyholes to store pieces of data for later use. Before using a variable you must declare it.  In the declaration you give the variable a name and you specify the type of data the variable will hold.   The declaration looks like:

type name

For example, on line 10 of AddEmUp above we declare a variable called total to be of type int (meaning it can hold an integer value).  In this particular declaration we set its initial value to be 0 although you do not need to do this during declaration.

The variable's type determines what kind of values it can hold and what operations can be performed on it.

You use the name of the variable to refer to the data the variable holds.  Variable names can be any legal identifier as long as they are not Java reserved words.  Identifiers can be any number of characters but must start with a letter.  They also must not contain spaces or most other non-alphanumeric characters.  In place of space, you can substitute the underscore character "_". 

The variable's scope is the block of code for which the variable is valid.  Scope also controls when the variable is created and destroyed as the program runs.  There are four kinds of variables we must distinguish:

  1. instance variables
  2. static variables
  3. local variables
  4. method parameters

As discussed previously, instance variables hold the state of a given object.  Each object has its own memory allocated to hold these values.

Each class may have its own static variables.  The name "static variable" is a bit of a misnomer.  It leads you to believe the value can't change, which is not the case.  Static variables are shared between all the objects of that class.  For example, a CDApp class could have a static variable called count to hold the number of CDApp objects that have been created.  Each time a new object is instantiated by calling the class's constructor, this value would be incremented.

Static and instance variables are also known as member variables.  They are declared within a class, but not within any of the class methods.  Their scope is the entire class, including the code in all the class methods.  The AddEmUp program declares one member variable called total on line 10.

Local variables are temporary cubbyholes that can hold a value while a particular piece of code is executing.  They are declared within the code of a method.  Their scope extends from the place they are declared to the closing curly brace "}" of the code block they are declared in.  The AddEmUp program declares the local variable number on line 19 to hold the current number being added to the total.

Method parameters serve as another type of variable.  We will discuss methods and their parameters in more detail in Lesson 12: Methods - Creation and Use.  At this point just know that method parameters are how values get passed into a method that may operate on them.  Line 17 of AddEmUp is the start of the method addUpTo().  This method has a parameter called upperLimit which is the upper limit of the numbers to add up.  This variable is referenced on line 21 where we test to see if we have added up enough numbers.

Data Types

In Java every variable must have a data type.  If you think of a variable as a cubbyhole, then the data type is the cubbyhole's shape.  You cannot put "square" data into a cubbyhole designed for "round" data.  Likewise, if you have declared a variable to be of type int as we did above, then you cannot put float (floating point or decimal data) into it.

Java has two categories of data types: primitive and object reference.  Primitive variables hold numbers, characters or booleans (true/false).  The primitive types are:



Object references hold pointers (or memory addresses) to an object instance.  For example, you could declare a variable called myTurtle to be of type Turtle and assign it an initial value like this.

    Turtle myTurtle = new Turtle();

You could later refer to myTurtle and have it move forward 10 pixels with the following code:

    myTurtle.forward(10);

In the AddEmUp example, we use the data type int when declaring the 3 variables on lines 10, 17 and 19.

Variables declared to hold an object reference may also be assigned the special value null.  This value means "no object."  For example, if you declare an instance variable of type Turtle but never assign it the value of an object, it contains the value null.

Literals

Literals are how specific values of Java primitive data types are represented in the source code.  For example, on line 10 of AddEmUp we initialize the variable total to a value of "0".  The "0" in the code is an integer literal.  Other examples of literals are:

103       // An int literal (could also be a short or byte)
true      // A boolean literal for 'true' ('false' is the other value)
3.14159   // A double literal for the value of PI
3.14159f  // A float literal (the "f" after it makes it a float rather
          // than a double)
'e'       // A char literal for the character e (the single quotes are
          // needed).

Besides literals for the primitive types, Java also provides literals for the String objects that hold strings of characters.

"Some string"   // A Sting literal (enclose the string in double quotes).

You can see examples of String literals in use on line 26.

Operators

Operators are things like the plus sign "+".  They perform functions like addition or subtraction on one or more values which are called the operands.  Operators can be unary, binary, or ternary.  A unary operator works on one operand.  For example,  ++ is a unary operator that increments the value of its operand by one.  Binary operators require two operands.  For example, + is a binary operator that adds its left and right operands together.  Finally, a ternary operator is one that has three operands.  The only ternary operator in Java is ?: which is a kind of if/else statement.

Operators perform an operation and return a result.  The data type of the result will generally depend upon the data type(s) of the operands.

Java has many operators.  The most commonly used are:

Arithmetic Operators

Operator

Use

Description

+

 op1 + op2

 Adds op1 and op2

-

 op1 - op2

 Subtracts op2 from op1

*

 op1 * op2

 Multiplies op1 by op2

/

 op1 / op2

 Divides op1 by op2

%

 op1 % op2

 Computes the remainder of dividing op1 by op2

++

 op++

 Increments op by 1; returns the value of op before incrementing.

++

 ++op

 Increments op by 1; returns the value of op after incrementing.

--

 op--

 Decrements op by 1; returns the value of op before incrementing.

--

 --op

 Decrements op by 1; returns the value of op after incrementing.



Relational Operators

A relational operator compares two values and returns true or false depending on the relationship between them.  They are commonly used in if() statements where you are testing the relation and conditionally executing a piece of code depending on the result.

Operator

Use

Returns true if

>

 op1 > op2

 op1 is greater than op2

>=

 op1 >= op2

 op1 is greater than or equal to op

<

 op1 < op2

 op1 is less than op2

<=

 op1 <= op2

 op1 is less than or equal to op2

==

 op1 == op2

 op1 is equal to op2

!=

 op1 != op2

 op1 is not equal to op2



Conditional Operators

A conditional operator works with true/false operands and returns a true/false value. 

Operator

Use

Returns true if

&&

 op1 && op2

 op1 and op2 are both true

||

 op1 || op2

 either op1 or op2 is true

!

 !op

 op is false

^

 op1 ^ op2

 if one or the other operand is true but not both



Assignment Operators

The basic assignment operator = is used to assign a value to a variable.   A typical usage might be:

     int i = 10 + 23;

which puts the value 33 into the variable called i.  New programmers are often confused by this notation since it look like an equality statement such as 2 + 3 = 5.  When using assignment statements, the value to the right-hand side of the = is assigned to the variable on the left-hand side.

There are also several shortcut operators that allow you to perform an operation and an assignment with only one operator.

Operator

Use

Description

=

 var = op

 assigns the value of op to variable var

+=

 op1 += op2

 equivalent to op1 = op1 + op2

-=

 op1 -= op2

 equivalent to op1 = op1 - op2

*=

 op1 *= op2

 equivalent to op1 = op1 * op2

/=

 op1 /= op2

 equivalent to op1 = op1 / op2

%=

 op1 %= op2

 equivalent to op1 = op1 % op2



Expressions, Statements and Blocks of Code

Expressions:

If you consider variables, operators and method calls to be "words" of the Java language, an expression is equivalent to a "phrase."  An expression is a series of variables, operators and method calls that evaluate to a single value.  The expression performs the computation specified as well as returns the value that is the result of the computation.  The code 2 + 3 is an example of a simple expression.

Statements:

Statements are somewhat similar to "sentences" in Java.  There are three types of statements to consider:

  1. expression statements
  2. declaration statements
  3. control flow statements

An expression statement can be constructed by combining one or more expressions and terminating them with a semicolon ";".  In the AddEmUp program above we have the following expression statements:


total = total + number;                 // increments total by the value
                                        // in number

System.out.println("Total is: + total); // Prints the resulting total
                                           on the console

A declaration statement declares a variable and optionally initializes it.  AddEmUp has the following declaration statement;

int total = 0;                          // declares the total variable
                                        // and initializes it.

Finally, control flow statements govern the order in which other statements get executed. The for loop and the if statement are examples of control flow statements. In AddEmUp we have the following control flow statement

while ( number <= upperLimit )

{
         ...
}

We will have much more to say about control flow statements in Lesson 11: Flow Control.

Blocks of Code:

The next level up in organization is a block of code.  This is roughly equivalent to a "paragraph" in the language.  A block is a grouping of zero or more statements between balanced curly braces.  Local variables can be defined within a code block, restricting their scope to within that block.

An important point about code blocks is that they may be used wherever a single statement would be allowed.  The code block is just treated as a somewhat more complex statement.  We will see this come into play in Lesson 11: Flow Control.