Contents:


Introduction

After completing Part 1 you should have Java installed and working on your computer. You should also have a basic idea how to compile and run a Java program from the command line using the java and javac commands. In this part I'm going to be looking at some of the basic components that make up a Java program. First, I'll talk about some of the different primitive data types that Java uses, such as integers and floating point numbers. Then I'll cover variables and how they are used by a program to temporarily store data. After that I'll go over some basic syntax rules and structure of Java programs. And finally, I'll end the lesson with some practice questions and exercises.

New Pop-up Information

Starting in this lesson you'll notice the This is an information pop-up. It should pop up and be displayed over and out of the flow of the paragraph text. icon scattered throughout the document. When you hover your mouse over one of these icons you should see a pop-up window that displays additional information. This is usually information that is important, but that may not necessarily fit with flow of the paragraph. I've tested it in Internet Explorer 6.0 and Firefox 1.02 and have had to make some compromises due IE's spotty implementation of some web standards, so hopefully it looks ok in your browser. If it doesn't display properly, please let me know by sending me an e-mail using link provided at the bottom of this lesson.

Primitive Data Types

At a basic level, most programs are just a means of inputting, outputting, and/or manipulating data in some way. Java classifies all data used in a program as belonging to a particular type. Of these data types there is a sub classification called "primitive types." These are sometimes known as "simple types" because they are atomic in nature. In other words, they are already in their simplest forms and can't be divided into any sub components. Among the primitive types represented in Java are integers (int), floating point numbers (float), characters (char), and boolean (true/false) values (boolean).

Integers

Probably one of the most familiar data types is the integer. An integer is a whole number such as 3, -7, 0, or 512. An integer in a Java program is the same as an integer in a math class, with a few exceptions. real integers have a range of negative infinity to positive infinity. So there's no real limit. Java integers, on the other hand, are limited to the range -2,147,483,648 to +2,147,483,647. This Java representation of an integer is called an int. The int keyword Java keywords are reserved words that have special meaning in the language. Click the icon for this box for more information. is used by Java to label a piece of data as an integer. You'll see how this works when I discuss variables.

Floating Point Numbers

Another commonly used data type is the floating point number. Floating point numbers are decimal approximations of rational (fractional) numbers. Some examples of floating point numbers and the fractions they approximate are 1.143 (117), 0.3333 (13), and 3.142857 (227). Floating point numbers are represented by the Java keyword float and have the following approximate ranges.
Approximate negative range:
-3.4030 x 1038 to
-1.4012 x 10-45

Approximate positive range:
1.4013 x 10-45 to
3.4028 x 1038

Characters

Java uses the char keyword to identify a character primitive data type. Characters can be divided into two types. The first type is the set of printable characters. These include letters, numbers, symbols, and even spaces. The second type of characters are often referred to as control characters, or meta-characters. Some examples of control characters are:
\t - The tab character
\n - The newline (line feed) character
\r - The carriage-return character
\f - The form-feed character
\a - The alert (bell) character
The back slash ('\') in front of each of those characters is used to indicate that these are special characters. For instance the character 'n' is literally the letter 'n', but the character '\n' is the newline character. When a backslash is used in front of a character it is called an escape sequence and a character in an escape sequence is said to be escaped. As you will soon see, escape sequences also come in handy for purposes other than specifying control characters.

Boolean Values

The boolean data type, represented in Java by the boolean keyword, can have only one of two possible values: true or false. In many programming languages, 0 can be used to represent a false value and any non-zero number can represent a true value. It's important to remember that Java does not use this convention. In Java, a boolean value can only have the value true or false, and attempting to assign any other type of value will result in an error when compiling.


There are more than four primitive data types. If you are interested, you can find a more complete list here. In the remainder of this lesson, however, I'll be sticking mainly to these four primitive types.

Variables and Operators

The discussion of data types may have seemed a bit abstract. If so, this section should help to clarify how data types are used in a program. Variables will be the main topic of discussion. A variable, simply put, is a named piece of data. Every variable has a name, type, size, and value.

Variable Name

A variable's name must be a legal identifier - a series of characters that begins with a letter. A variable name can contain letters, numbers, and/or underscores ('_'), but cannot contain spaces, or be the same as a Java reserved keyword. Here are some examples of legal and illegal identifiers:
oneNumber  - legal
1number    - illegal: Begins with a number
numberOne  - legal
number1    - legal
number one - illegal: contains space
number_one - legal
false      - illegal: this is a Java reserved word
Another point to remember when naming variables is readability. Make your variable names reflect the variable's purpose. For instance, a variable that holds an account number would be named something like: accountNumber. You could also call it account_number, but it is a very common practice among programmers to use what is called Camelcase. Camelcase is simply capitalizing the first letter of each successive word in a variable name. firstName, lastName, and socialSecurityNumber are all examples of this. Notice the first letter of the variable name is not capitalized. Camelcase calls for the first letter of certain types of variables to be capitalized. I will get to those in later lessons. For now just use this convention.

Variable Type

As previously mentioned, every variable also has to have a type. A variable's type and name are specified when it is declared in a program. A variable must be declared before it can be used. Let's say I need a variable to hold a random integer. The declaration would look something like this:
int randomInteger;
The first part of any variable declaration is the variable type. The second part is the variable name. In this example the variable is of type int (integer) and is named randomInteger. You may have also noticed a semicolon. That's not a typo. The semicolon is what is known as a line delimiter. It's required at the end of any Java statement. This, and other basic Java syntax, will be covered in more detail later in this lesson.

Value Assignment

Once a variable has been declared, it may be given a value. Here is how I would assign a value to the integer variable I just declared.
randomInteger = 5;
In this example I have used the assignment operator ('=') to set the variable equal to 5. An operator is a symbol, or combination of symbols, that perform some function. In this case the assignment operator performs the function of assigning a value to a variable. More specifically, the assignment operator is a binary operator because it works on two operands: the integer variable randomInteger and the literal integer 5. A value may also be assigned to a variable when it is declared, like so.
int anotherRandomInteger = 10;
Here I have declared an integer variable named anotherRandomInteger and assigned it the value 10 at the same time. Assigning an initial value to a variable before it's used is known as initialization of the variable. It is often good programming practice to initialize variables to some standard value. For example, you might decide to initialize all integer variables to 0, all float variables to 0.0, and all boolean variables to false in their declarations. Then, later in the program, you could assign new values as needed.

Arithmetic Operators

Java supports several arithmetic operators for integers and floating point numbers. These include + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). I'm sure you're familiar with the first four operators, but the fifth may need some explaining. The "percent symbol" ('%') is called the modulus operator. The modulus operator simply divides two numbers, but instead of returning the result of the division, it returns the remainder. Here is an example of arithmetic operators in use.

// File must be named SimpleArithmetic.java
public class SimpleArithmetic
{
    public static void main( String args[] )
    {
        // Declare all variables
        int integerOne = 5;
        int integerTwo = 2;
        int sum = 0;
        int difference = 0;
        int product = 0;
        int remainder = 0;
        float dividend = 0;
       
        // Add integers and assign value to sum
        sum = integerOne + integerTwo;
       
        // Subtract int variables and assign value to difference
        difference = integerOne - integerTwo;
       
        // Multiply int variables and assign value to product
        product = integerOne * integerTwo;
       
        // modulo int variables and assign value to remainder
        remainder = integerOne % integerTwo;
       
        // divide int variables and assign value to dividend
        dividend = integerOne / integerTwo;
    }
}
For now, let's focus on the portion of the program that's relevant to our discussion of variables and operators. I'll be covering some basic structure and syntax later in this lesson. As you can see, in the first part of the program I'm declaring and initializing the variables. I set integerOne to 5, integerTwo to 2, and the rest to 0. After the declarations are some arithmetic operations. First, I've assigned the result of the expression integerOne + integerTwo to the variable sum. Generally, you can think of an expression as something that returns a value. So, 1 + 1 is an expression because it returns the value 2. And expressions are not just limited to mathematics. The returned value of an expression could be anything from someone's name to the half-life of carbon 14 (approximately 1.81 x 1011 seconds). So, getting back to the example, sum would now have the value 7 because integerOne (5) plus integerTwo (2) is 7. It might seem obvious, but assignment statements are evaluated by the Java compiler from right to left. So anything to the right of the = operator will be evaluated or calculated first and then assigned. Predictably, the value of difference is 3, product is 10, and reminder is 1. But the value of dividend may not be so obvious.

In Java, when integers are divided an integer value is returned. This implies that if the result of the division is a normally floating point number, then some data will be lost. In our example we are dividing 5 by 2. The usual result of this is 2.5, which is a floating point number. In Java, however, integer division cuts off everything after the decimal place. So, even though dividend is of type float, the result of the expression integerOne / integerTwo is still 2. Don't confuse this behavior with rounding. Regardless of what the value after the decimal place would have been, it gets cut off and only the integer portion is returned. Even 2.99999 would be returned as 2. So, in this case dividend would have the value 2.0. I could have declared integerOne and integerTwo as float variables to begin with, which would have allowed the more precise value of 2.5 to be assigned to dividend, but there is another way to accomplish this without changing variable types.

Casting

It is sometimes desirable to change the data type that is returned from an expression. In our previous example we wanted to get the more precise result of dividing 5 by 2, which is 2.5. One way to achieve that would be to cast the integer variables as float variables. Casting means changing the data type of the returned value. This doesn't change the data type of the variables. It only affects their returned value type for the duration of the arithmetic operation. Here's how that would look in our previous example.
dividend = (float)integerOne / (float)integerTwo
So, in this example the value of integerOne is cast to 5.0 and the value of integerTwo is cast to 2.0 and the resulting expression 5.0 / 2.0 returns the value of 2.5, which is assigned to dividend. This is what is known as explicit casting because I explicitly stated the type, in parentheses, next to the variable I was casting. Sometimes, however, values are cast to other types implicitly. An example of this is multiplying or diving an integer with a floating point number. Anytime an int is multiplied or divided with a float, the int is implicitly cast to type float during the arithmetic operation and the result is returned as float. Here are some examples.
5 / 2     (= 2)
5.0 / 2.0 (= 2.5)
5.0 / 2   (= 2.5)
5 / 2.0   (= 2.5)
5.0 * 2   (= 10.0)
Implicit casting often occurs when one data type can be safely converted to another without any loss of precision or data. So an int value can be implicitly cast by the compiler to type float because there is no way to lose precision. However, when the possibility of losing precision occurs, then explicit casting must be used. Here are some examples of implicit and explicit casting.
someInteger = (int)someFloat; // Explicit cast of a float to an int
someFloat = someInteger;      // Implicit cast of an int to a float
The first example is assigning the value of a float variable to an int variable. In this case, if someFloat is not explicitly cast to type int then a compiler error occurs. In this case, explicitly casting is like telling the compiler that you are aware of the possible loss of precision and that it's ok. Since there is no way to lose precision when going from int to float, in the second example someInteger is implicitly cast to type float by the compiler and then assigned to someFloat.

Memory Concepts

Earlier I said that a variable is a named piece of data. For the most part, this is correct, but it doesn't tell the whole story. The variable itself is just a label that refers to a location in your computer's memory. This memory location is where the actual data resides. When you declare a variable, Java reserves space in memory for the data that will go there. So the amount of memory reserved depends on the type of variable declared.

int integerOne; Shown above is a very simplified model of your computer's memory represented by a table. After being declared, the label integerOne now refers to a memory location that is the size required to store the largest possible Java int. So, the variable name is independent of the data itself. Now let's assign data to a variable:

integerOne = 5; Now the integerOne variable's memory location contains the value 5. This value will persist in that memory location until the part of the program that uses the variable ends. Once that happens, Java will discard the variable name and release this memory location to be used by some another variable or program. In the next example I'm declaring another variable and initializing it to the value of integerOne;

int integerOneCopy = integerOne; As you can see, when a primitive type is assigned the value of another primitive type variable, it creates a copy of the data in a separate memory location. This behavior is called copying by value. As you'll see in later lessons, not all variables behave this way.

Basic Syntax and Structure

When writing a Java program there are several "pieces" that must be included. In this section I'm going to talk about those required pieces and some of the basic syntax you'll need to know about before you can begin writing your own applications.

Basic Structure

You've already seen a few examples of simple Java programs. In each example, the code The word code is generally used to refer to source code. This could be an entire program or just a piece of it. I'll probably be using this term quite a bit from here on. was encapsulated (contained) within a class. Inside this class there was always something I called the main() method. And encapsulated within this main() method was the actual program statements. I'm mentioning these two things because they are necessary in every Java program. But don't worry about what a class or a method is just yet. We'll get to that later.
// File must be named SomeClass.java
public class SomeClass
{
    public static void main( String args[] )
    {
        // Program statements go here
    }
}
When structures are placed within other structures like this, it is called nesting. The main() method is said to be nested within the SomeClass class. Also note that the first letter of SomeClass is capitalized. It is a common naming convention for class names to be capitalized, as opposed to variables, which are not. I'll talk about classes in later lessons when I cover object oriented programming concepts. For now, just remember that you'll need to begin your program with the beginning of the class definition, which includes the keywords public class followed by your class name and then followed by an open brace, {. All braces, brackets, and parentheses come in pairs, so there must always be an even number of them. A common programming error is to forget to type a closing brace. Sometimes working with nested blocks of code can get confusing. So it's good to get into the habit of typing the open brace, {, hitting Enter a couple of times, and then typing a closing brace, }. You can then type your code in between the braces. This helps to ensure that you don't forget one. Generally open braces signify the beginning of a block of code. This open brace signifies the beginning of your class. It's not required, but it's common practice for programmers to indent everything between braces. This makes the program more readable because braces line up.

As mentioned, the main() method is nested within the class code block. The main() method is part of the class that encapsulates it. It's the part of any program that causes it to execute. Without a main() method a program will not run. For now, just remember to always write the main method exactly as it is in the above example. The different parts of it will be explained when I discuss methods in a later lesson.

Basic Syntax

The word syntax is just a fancy way of saying, "the way in which something is put together." You could also think of syntax as a set of rules. Just like spoken languages, Java has rules that must be followed in order to "communicate" with the compiler. As I mentioned earlier, all statements must end with a semicolon. The only exception to this rule are code blocks. As you can see from the example, code blocks don't use semicolons at all, but the statements inside them do.
// File must be named SomeClass.java
 public class SomeClass
{
    public static void main( String args[] )
    {
        // Declare the variables
        int integerOne;
        int integerTwo;
        int result;
        
        // Long calculation broken into
        // several lines for readability
        result = (integerOne / integerTwo) +
                 (integerOne * integerTwo) +
                 (integerOne / integerTwo) -
                 (integerOne * integerTwo);
        
    } // No semicolon
} // No semicolon
Another characteristic of Java's syntax is that it ignores excessive whitespace. Whitespace is just the word used for tabs, spaces, and anything that takes up space but is not visible.
// File must be named SomeClass.java
 public class SomeClass
{
    public static void main( String args[] )
    {
        int         integerOne=5;
        
        int integerTwo  =10;
        
        int result=integerOne +integerTwo;
        
        int    resultTwo    =   integerOne  +   integerTwo;
    }
}
In this example, all of these statements are correct. Obviously, using spaces wisely is to your benefit. It makes programs much easier to read. Taking a little time to add spaces, line breaks, indentions, and comments to your programs can be of enormous benefit later on.

Practice

Now that you've read through this tutorial, you should be capable of creating some simple programs.

  1. What operator would you use to determine if a number is divisible by 2?
  2. Is package a legal variable name? How about Package? Why or why not?
  3. Create a program that declares two integer variables and a float variable. Assign one first variable the value of 33, the second variable the value of 4, and the last variable the result of variable one divided by variable two. Make sure the value in variable three is the precise float value.
  4. Create a program that declares any number of integer variables and assigns their average to a float variable. Then output the average to the console. Hint: Remember outputting text to the screen from lesson one? You can use the same statement, but replace "Hello World!" with the variable name that holds the average (minus the quotes)

If you have any questions or comments, feel free to post them at the Dream.In.Code Java forum. If you're not registered, go ahead - it's free. If you have any technical difficulties with this page, of if you find a mistake or typo, please let me know by sending me an email.

Further Reading

I just want to say thanks to my friends at Deitel and Associates for their great programming resources. If you're interested in a more in-depth coverage of Java please check out

Java How To Program 6th Edition.