2a

Advanced Placement

Computer Science Lab

 

 

Identifiers, Primitive Data Types and Operators

 

Introduction

 

In this lab we will write some Java programs in which we explore the use of identifiers, primitive data types and operators.  We will be using the IDE JCreator that we introduced in the previous labs to write, compile, edit, and run our programs. Also we will be adding the use of additional import statements and packages, which will allow us to increase the complexity of our programs.

 

 

 

A. Identifiers.

 

Identifiers are the name for any variable, parameter, constant, user defined method or user defined class. Identifiers cannot be key or reserved words.  Since Java is case sensitive, you must be careful to not change the case on an identifier, e.g. age and Age would refer to different variables.  An identifier must start with a letter, an underscore (_) or a dollar sign ($).  An identifier cannot contain an operator such as +, , *, / or %.  An identifier can be of any length.  Good programming style suggests that identifiers be descriptive of what they are identifying, e.g. radius instead of r.  The convention that many Java programmers follow  (and that we will too) is the following:

 

(1) class names are begin with an upper case letter and may have internal upper case letters, e.g. MyClass.

(2) method names start with a lower case letter but may have internal upper case letters, e.g. myMethod().  Note that methods will always have a set of parentheses at the end.

(3) variables start in the lower case and may have capitalize parts internally, e.g. preTaxProfit. 

 

 

 

B. Primitive Types.

 

While Java is a language based on classes, not all data types are classes.  In fact the Java data types can be divided into two groups, primitives and reference types.  Reference types, in addition to classes, include interfaces and arrays, all of which we will go into detail about later.  Primitive data types refer to the data types that are used to describe characters, numbers and a true or false condition. Java is a strongly typed language in as much as variables must by declared of a certain type.  This is because the variable is then given a specific amount of memory.  In Java there are eight primitive types, with each requiring a specific amount of memory.  The eight types are shown in the table below. 

 

 

 

Name

Description of Domain

Example

Storage Size

byte

27 to 271

22

8 bit, 1 byte

short

215 to 2151

-2303

16 bit, 2 bytes

int

231 to 2311

34567891

32 bit, 4 bytes

long

263 to 2631

890789345689

64 bit, 8 bytes

float

3.4E38 to 3.4E38 (6 to 7 significant digits)

6.67856

32 bit, 4 bytes

double

3.4E308 to 3.4E308 (14 to 15 significant digits)

3.412348989045

64 bit, 8 bytes

boolean

true or false

 

 

char

Unicode character set

 

16 bit, 2 bytes

 

 

 

 

In writing programs you must be careful to make sure that you do not assign a variable of one primitive type to a variable of another primitive type with a smaller amount of memory.  This will typically result in a compiler error.  Also, you must be careful that your program does not attempt to store a value larger than the variable type in the variable.  If you do this it will result in an overflow error. For the purposes of the AP exam, the types that are used are int, double, and boolean.  Obviously, the type of identifier used most in a program is probably the variable.  Variable must be declared to be of a certain type before they are used.  If they are not declared prior to use you will get a compiler error.  Variables can also be declared and initialized in the same statement as shown in the code fragment below:

 

           

 

int y;          //declare y to be an integer variable

double radius   //declare radius to be a variable of type double

double area = 45.6; //declare and initialize variable area

char a = ‘A’    //declare and initialize a variable of type char

 

 

 

 

 

C. Operators.

 

There are four types of operators that are used in Java programming: arithmetic, assignment, relational and logical.  The following table shows the arithmetic operators:

 

 

 

 

Operator

Meaning

Example

+

addition

7 + y

subtraction

r – s

*

multiplication

5 * i

/

division

10/4  returns 2 not 2.5

%

mod (remainder)

22 % 3 returns 1

 

 

 

 

If int and double occur in the same expression, the int will be promoted to a double.  An int % int will return an int.  When an int / int results in a decimal, the decimal is dropped, i.e. 7/8 would produce a zero answer. The order of precedence for the operators is the same as expected in algebra, i.e. parentheses from inner to outer, then *, /, %, +, - (lowest).  Operators at the same level of precedence

 

 

 

 

 

Operator

Meaning

Example

=

assignment

x = 7

+=

x = x + 7

x += 7

=

x = x 7

x = 7

*=

x = x * 7

x *= 7

/=

x = x / 7

x /= 7

%=

x = x % 7

x %= 7

 

 

 

 

 

Generally, the only assignment operators that are used with frequency are the = and the +=. We will discuss in greater detail the relational operators and the logical operators when we start to talk about conditional statements and control structures in successive lab exercises.  Note that assignment is not the same as equal.  Assignment means take whatever is evaluated on the right hand side of the assignment operator and place it in the memory location designated on the left hand side of the assignment operator.  This means that x = x + 1 in a program is a perfectly valid expression even though it would not be allowed in basic algebra.

 

 

 

 

D. Primitive Type Conversion.

 

As we noted, the reason that Java is strongly typed is that the primitive types have a fixed size in terms of the number of bytes.  This does not, however, preclude a programmer from converting a variable of one type into another.  In going from a smaller type to a larger (e.g. int to double) there is little problem, However, in going from a larger to a smaller there may be a loss of information.  Because of this loss of information a type conversion from larger to smaller must be explicitly cast by the programmer.  This is done as follows:

 

 

 

 

 

          int testInt;

          double testDouble;

         

          //not necessary to recast

          testDouble = testInt;

         

          //recast double as int

          testInt = (int)testDouble;

         

 

 

 

 

 

Procedure

 

 

 

A.  Testing Primitive Types

 

1.         Open JCreator.  Open the "JavaProjects" workspace.  Create a a new empty project labeled "PrimitiveTypes". 

 

2.         Now select Project  à  New  à  Class  and name the class in this project  Keyboard. Go to the AP Computer Science utilities folder on the Lab Exercises page of the class website and copy the text file named Keyboard.java.  Copy the contents of the file onto the clipboard and then paste the contents into the Keyboard workspace in JCreator.  Notice that the first line of the source code is "package APSC". This tells the compiler that components of this class are going to be used in other classes.  Compile the class to make sure that it has no errors.

 

3.         Now select Project  à  New  à  Class.  In the dialog box where it asks for the name type PrimitiveType.

 

4.         Now click on the button marked Finish. Notice that your workspace now has a tab with a file named Keyboard.java and another for PrimitiveType.java.

 

5.         Replace the code fragment in PrimitiveType.java  with the following code:

 

 

 

 

           

/*

PrimitiveType - Application

Version 1.0 (xx/xx/xx)

Program prompts user to enter an

integer and converts it to a double

*/

 

import APCS.Keyboard;

 

class PrimitiveType

{

  public static void main (String args[])

  {

     int testInt;

     double testDouble;

    

     System.out.print("Enter an integer ");

     testInt = Keyboard.readInt();

     System.out.println("The interger is: " + testInt);

    

     testDouble = testInt;

    

     System.out.println("The double is: " + testDouble);

    

    

  }//end main

}//end TestPrimitive

 

 

 

 

 

5.         Compile the code and then execute the code a couple of times with different integers.  What happens when you try to use a non-integer?  What happens to the integer value when it is output as a double?

 

6.         Now replace the code so that it looks like the following:

 

 

 

 

/*

PrimitveType - Application

Version 1.0 (xx/xx/xx)

Program prompts user to enter a number

*/

import APCS.Keyboard;

 

class TestPrimitive

{

     public static void main (String args[])

     {

          int iResult = 0;

          int iTest1 = 18;

          int iTest2 = 23;

          double dResult = 0;

          double dTest1 = 14.78;

          double dTest2 = 82.56;

         

          System.out.println("double 1 is: " + dTest1);

          System.out.println("double 2 is: " + dTest1);

         

          System.out.println("int 1 is: " + iTest1);

          System.out.println("int 2 is: " + iTest2);

          iResult = iTest1 + iTest2;

         

          System.out.println("The double as an int is: " + iResult);

         

         

     }//end main

}//end TestPrimitive02

 

 

 

 

 

 

 

 

 

 

7.         Compile and run.  What happens?

 

8.         Change the operator to the other four operators and see what happens with each.  Change the iResult variable to the dResult variable and see what happens.

 

8.         Compile the code and then execute the code a couple of times with different integers.  What happens when you try to use a non-integer?  What happens to the integer value when it is output as a double?

 

Programming Assignment

 

 

 

 

Write a program that print a list of at least 5 student's name together with their grades for various assignments (labs, tests, homework and total in the format shown below:

 

 

 

 

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

             Student Points

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

 

Name           Test      Lab       Total

Smith, James  22        13        35

Johnson, Mary 38        20        58

 

 

 

 

 

 

Requirements for the program are to print the border as above, use tab characters to get your columns to align, and use the plus operator for both the addition and the string concatenation.

 

Make up your own student names and points.  You need a minimum of 5 names.