STUDENT OUTLINE

Lesson 1 - Data Types in Java


INTRODUCTION:

As with most high level languages, Java provides standard data types to store information. Java is a richly typed language which gives the programmer a wide variety of data types to use. In this lesson you will declare variables, store values in them, and print out their values using the System.out object.


The key topics for this lesson are:

A. Identifiers in Java
B. Basic Data Types in Java
C. Declaring and Initializing Variables in Java
D. Printing Variables Using the System.out object
E. ASCII Code Values and Character Data
F. Assignment Statements and Math Operators
G. Formatting Output

VOCABULARY:

IDENTIFIER
integer
char
ESCAPE SEQUENCE
TYPE CONVERSION
MODULUS

KEYWORDS
float
ASCII
TYPE
ASSIGNMENT STATEMENT
boolean

DISCUSSION:

A. Identifiers in Java

1. An identifier is a name that will be used to describe classes, methods, constants, variables, and other items.

2. The rules for writing identifiers in Java are:
a.  Identifiers must begin with a letter.
b.  Only letters, digits, or underscore may follow the initial letter.
c.  The blank space cannot be used.
d.  Identifiers cannot be reserved words. Reserved words or keywords are identifiers reserved for system use.

3. Java is a case sensitive language. Java will distinguish between upper and lower case letters in identifiers. Therefore:

        grade versus Grade are different identifiers

4. A good identifier should also be a mnemonic device which helps describe the nature or purpose of that function or variable. It is better to use

        grade instead of g, number instead of n.

Remember that our goal is to write code that is easy to read and professional in nature.

5. Programmers will adopt different styles of using upper and lower case letters in writing identifiers. The reserved keywords in Java must be typed in lower case text, but identifiers can be typed using any combination of upper and lower case letters.

6. The following conventions will be used throughout the curriculum guide:

a.  A single word identifier will be written in lower case only. Examples: grade, number, sum.
b. If an identifier is made up of several words, the first letter will be lower case. Subsequent words will begin with upper case. Some examples are: stringType, passingScore, largestNum.
c. Identifiers used as constants will be fully capitalized. Examples: PI, MAXSTRLEN.

B.  Basic Data Types in Java

1. Java provides eight primitive data types: byte, short, int, long, float, double, char and a boolean.

a. The data types byte, short, int, and long are for integers.
b. The data types float and double are for real or "floating point" numbers.

2. Integer type - any positive or negative number without a decimal point.

Integer examples: 7, -2, 0, 2025

3. Floating Point type - any signed or unsigned number with a decimal point.

Floating point examples: 7.5    -66.72     0.125    5.     3f    28d

A floating point value can be specified by
a. a decimal point. e.g. 5. , -3.1415
b. an integer number appended by an f or F, d or D. e.g. 2011f, -345d
c. scientific notation. e.g. 1625. = 1.625e3        .000125 = 1.25e-4

A floating point value cannot contain a comma or $ symbol. e.g. 1,234.56    $66.95

4. The following table summarizes the bytes allocated and the resulting size.

Size Minimum Value Maximum Value
byte 1 byte -128 127
short 2 bytes -32768 32767
int 4 bytes -2147483648 2147483647
long 8 bytes -9223372036854775808 9223372036854775807
float 4 bytes -3.40282347E+38 3.40282347E+38
double 8 bytes -1.79769313486231570E+308 1.79769313486231570E+308

5. Character type - letters, digits 0..9, and punctuation symbols.

a.  Examples:    'A',    'a',    '8',    '*'
b.  Note that a character type must be enclosed within single quotes.
c.  Java character types are stored using 2 bytes, usually according to the ASCII collating sequence. ASCII stands for American Standard Code for Information Interchange.
d.  The character value 'A' is actually stored as the integer value 65. Because a capital 'A' and the integer 65 are physically stored in the same fashion, this will allow us to easily convert from character to integer types, and vice versa.
e.  Using the single quote as a delimiter leads to the question about how to assign the single quote (') character to a variable. Java provides escape sequences for unusual keystrokes on the keyboard. Here is a partial list:

Character Java Escape Sequence
Newline '\n'
Horizontal tab '\t'
Backslash '\\'
Single quote '\''
Double quote '\"'
Null character '\0'

6. Data types are provided by high level languages to minimize memory usage and processing time. Integers and characters require less memory and are easier to process. Floating point values require more memory and time to process.

7. The final primitive is the type boolean. It is used to represent a single true/false value. A boolean value can have only one of two values:
        true         false
In a Java program, the words true and false are reserved words that always mean these boolean values.

C.  Declaring and Initializing Variables in Java

1. A variable must be declared before it can be initialized with a value. The general syntax of variable declarations is:

        <datatype>    <variableName>;

2. Variables can be declared near the top of the method or in the midst of writing code. Variables can also be declared and assigned a value in one line. The following example program illustrates these aspects of variable declaration and assignments.

 Program 3-1

  public class DeclareVar
  {
     public static void main(String[] args)
     {
          // first is declared and initialized
          // second is just intialized
          int first, second; 
          double  num = 2.5;
          char ch;
          boolean done;

          first = 5;
          second = 7;
          num = 3.5;
          ch = 'T';
          done = false;

          int sum = first + second;
     }
  }
  

In Program 3-1, two variables, first and second, are declared on the same line, the variable num is declared and assigned the value 2.5, and the variable sum is declared and assigned the computed value first + second.

3. Where the variables are declared and initialized is a matter of programming style. Your instructor will probably have some preferences regarding this matter.

D.  Printing Variables Using the System.out Object

1. The System.out object is defined in each Java program. It has methods for displaying text strings and numbers in plain text format on the system display (console). For example:

 Program 3-2

  public class PrintVar
  {
     public static void main(String[] args)
     {
         int  number = 5;
         char  letter = 'E';
         double average = 3.95;
         boolean done = false;

         System.out.println("number = " + number);
         System.out.println("letter = " + letter);
         System.out.println("average = " + average);
         System.out.println("done = " + done);
         System.out.print("The ");
         System.out.println("End!");
     }
  }

  Run output:

  number = 5
  letter = E
  average = 3.95
  done = false
  The End!
  

2. Method System.out.println displays (or prints) a line of text in the console window. When System.out.println completes its task, it automatically positions the output cursor (the location where the next character will be displayed) to the beginning of the next line in the console window (this is similar to pressing the Enter key when typing in a text editor—the cursor is repositioned at the beginning of the next line in your file).

3. The expression

      "number = " + number
  

from the statement

      System.out.println("number = " + number);
  

uses the + as an operator to “link” or concatenate two strings. The result of this operation is a new, and normally longer string. String concatenation is discussed in more detail in the next lesson.

4. The lines

      System.out.print("The ");
      System.out.println("End!");
  

of Program 3-2 display one line in the console window. The first statement uses System.out’s method print to display a string. Unlike println, print displays the argument and positions the cursor after the last displayed character in the console window.

5. Note the distinction between sending a text constant, "number = ", versus a variable, number, to the System.out object. Each variable will be printed out as represented by its declared data type, integer variables printed out like integers, boolean as true/false, and so forth.

E.  ASCII Code Values and Character Data

1. As mentioned earlier in section B.5, a character value can easily be converted to its corresponding ASCII integer value.

2. A character value is stored using two bytes of memory, which consists of 16 bits of binary (0 or 1) values.

3. The letter 'A' has the ASCII value of 65, which is stored as the binary value 0000000001000001. This is illustrated in the following program fragment:

    char letter = 'A';
    System.out.println("letter = " + letter);

    System.out.print("its ASCII position = ");
    System.out.print((int)letter);

    Run output:

    letter = A
    its ASCII position = 65
  

The statement (int)letter is called a type conversion. The data type of the variable is converted to the prefix parenthesized type (int), if possible.

4. In Java, you can make a direct assignment of a character value to an integer variable, and vice versa. This is possible because both an integer and a character variable are ultimately stored in binary. However, it is better to be more explicit about such conversions by using type conversions. For example, the two lines of code below assign position the ASCII value of letter.

    char letter = 'C';  // ASCII value = 67
    int position;

    position = letter;  // This is legal, position now equals 67
  

                         vs.

    position = (int)letter;  // This is easier to understand.
  

F.  Assignment Statements and Math Operators

1. An assignment statement has the following basic syntax:

               <variable>   =   <expression>;

a.  The can be a literal constant value such as 2, 12.25, 't'.
b.  The can also be a numeric expression involving operands (values) and operators.
c.  The = operator returns the value of the expression. This means that the statement

    a = 5;
  

also results in the value 5. This allows for chaining of assignment operators.

    a = b = 5;
  

The assignment operator (=) is right-associative. This means that the above statement is really solved in this order:

    a = (b = 5);// solved from right to left.
  

Since (b = 5) returns the integer 5, the value 5 is also assigned to variable a.

2. Java provides 5 math operators as listed below:

+  Addition, as well as unary +
-  Subtraction, as well as unary -
*  Multiplication
/  Real and integer division
%  Modulus, remainder of division

3. The numerical result and data type of the answer depends on the type of operands used in a problem.

4. For all the operators, if both operands are integers, the result is an integer. Examples:

    2 + 3 = 5  (integer)	9 - 3 = 6  (integer)
    4 * 8 = 32 (integer)	11/2 = 5  (integer)
  

5. If either of the operands is a float type, the result is a float type. Examples:

    2 + 3.000 = 5.000  (float)
    25 / 6.75 = 3.7037 (float)
  

a.  When an integer and a float are used in a binary math expression, the integer is promoted to a float value, then the math is executed.
b.  In the example 2 + 3.000 = 5.000, the integer value 2 is promoted to a float (2.000) and then added to the 3.000.

6. The modulus operator (%) returns the remainder of dividing the first operand by the second. For example:

      10 % 3 = 1    2 % 4 = 2   16 % 2 = 0   27.475 % 7.22 = 5.815
  

7. Changing the sign of a value can be accomplished with the negation operator (-), often called the unary (-) operator. A unary operator works with only one value. Applying the negation operator to an integer returns an integer, while applying it to a float returns a float value. For example:

      -(67) = -67      -(-2.345) = 2.345 
  

8. To obtain the fractional answer to a question like 11/2 = 5.5, a type conversion must be applied to one of the operands.

      (double)11/2	results in 5.5
	11.000/2	then we solve division
	5.5
  

The type conversion operators are unary operators with the following syntax:

      (type) operand
  

9. There is more to cover regarding operators in Java. Topics such as math precedence and assignment operators will be covered later.

SUMMARY/ REVIEW:

This lesson has covered a great amount of detail regarding the Java language. At first you will have to memorize the syntax of data types, but with time and practice fluency will come.

G.  Formatting Output

Often what we see as output has been formatted so it is easier for us to read. For instance, the return address on a letter might look like this:

Fred Jones
345 Main Street
Cupertino, CA 95014

Fred's address is left justified. Similarly, a sign off at the end of the letter might be center justified. When you show an approximate answer to a math problem, you might format the decimal, showing only two places.

We will use two ways to format output in our class. We'll use (a) Format class, which was written by another Java developer, but has not been adopted to be added to the Java API. We'll also use (b) printf, which is a method popularized in C language.

Format class has three methods to handle each of the directions of justification: left, right, and center. There are actually several version of each method, which differ based on the number of parameters (what is in the parentheses) given. For instance, one version of left() accepts an additional parameter (the last one) to indicate how many decimal places to show. Each method's syntax is: Format.method(variableFormatted, field Width, decimalPlaces) with all parameters being integers and the last parameter only being required when the variable formatted is a decimal. Variables or literal values can be used for variableFormatted. Here are some examples:

System.out.println(Format.center("Hello", 5));
shows Hello printed in the center of the page (field width 5)

System.out.println(Format.left("Hello", 2));
shows 2 letters of Hello at left (in a field width of 2 spaces)

System.out.println(Format.right(5.123345, 10, 2));
shows 5.12 to the right in a field width of 10 spaces

double y=1.0;
System.out.println(Format.center(y, 10, 5));
shows 1.00000 center justified on screen

printf is a method that can left or right justify. It also accepts "flags" which can indicate if you want to change field width or display limited numbers of places for decimals. Because it is written in C, its syntax looks different from Java. Because of Java's design to work well with other languages, you can add this C method within Java code and it will compile and execute without issue. In C, a single letter indicates the data type being formatted; 's' indicates if a String is being used, 'i' or 'd' is used for integers, and 'f' is used for a decimal (floating point) type. There are additional options your teacher may allow you to use in class. Signs '-' and '+' can be added to change from the default behavior (right justification with no number sign shown on numbers). Add '-' in front to left align. Add '+' to show a number sign. The integer preceding the data type indicates field width. A number following field width, with a decimal preceding it, indicates how many places to show.

For instance:
System.out.printf("%s \n", "Hello");
prints right justified Hello, then skips to the next line

int y = 8;
System.out.printf("%d", y);
prints 8 right justified

System.out.printf("Dec is %-10.3f", 987.654321);
prints 987.654 left justified in a field width of 10



Back to Java Main Page