CompSci-61B Lab 1b
Variable and Objects

Instructor: Prof. Robert Burns

For a computer program to do anything useful, it has to be able to store "values" and manipulate them. The kinds of values that can be stored in Java programs are separated by type: numbers and text. Then numbers are further separated into whole numbers and floating point numbers, and text is further separated into single-character text and any-length text. It is important for a Java programmer to always be aware of the "data type" of a value in a program. (This is not the case for Javascript, PHP, and Basic programmers, by the way.)

In the body of a Java program, the way in which a value is written tells its type. Here are some examples:

Note that floating points have a decimal point, even if it is not needed to represent the number (like -40). Single-character text is offset with apostrophes, and any-length text with quotes.

Values can be sent directly to output, as we did with any-length text in lab 1a. But values can also be stored in computer memory for later use and manipulation (such as arithmetic expressions). To store a value, the programmer creates a "variable", to reserve addressable memory, and writes an "assignment statement" to store a value in the variable. Here are some examples for each of the four data types:

  int age;             double gpa;             char grade;              String name;
  age = 21;            gpa = 4.0;              grade = 'A';             name = "Robert Burns";

In each pair of statements, the first is a "declaration statement" that tells the data type and name of a variable. The equal sign in the second "assignment statement" is not an expression of equality, as it is in algebra. It would be better to write it as age <- 21;, indicating that the value on the right gets stored into the variable on the left. But the Java language uses the equal sign, which is easier to type.

The statements can be combined, too, into a single "assignment upon declaration" statement, like these:

  int age = 21;        double gpa = 4.0;       char grade = 'A';        String name = "Robert Burns";

Note that String is a capitalized word, while the others are all not so. The reason is that String is a special kind of variable, and any-length text is a special kind of value. The value is what's known as an "object", and the variable is a "reference to the object". For int, double, and char, the value is stored directly in the memory that got reserved for the variable. That's possible because the number of bytes of memory needed to store the value is predictable based on the data type. But that is not the case for any-length text, in which the number of bytes needed to store the value depends on the value and not on the data type. So the value is actually stored in another part of memory, and the String variable simply stores the memory location of the value -- it's like a middle-man!

A feature of Java that will be very important in our future studies in this class is "generics". This feature works with objects only -- that is, not with int values. So for consistency, Java allows declarations for int values and others that look and act like objects, although they are still just simple values. Here are the declaration and assignment examples, that are interchangeable with the statements above:

  Integer age;         Double gpa;             Character grade;
  age = 21;            gpa = 4.0;              grade = 'A';

Numeric values can be manipulated with arithmetic expressions, using "operators" for addition (+), subtraction (-), multiplication (*), division (/). They can be used on the right-hand side of an assignment statement, like this:

  two = 1 + 1;         pricePlusTax = 3.99 * 1.0825;         tempF = 1.8 * tempC + 32.0;
  root1 = (-b * Math.sqrt(b * b - 4.0 * a * c)) / (2.0 * a);

Note the use of parentheses and the square root library function in the root1 assignment. And remember -- you cannot assign a value to a variable that has not been declared, and your cannot use a variable for which no value has been assigned. So you can assume that the declaration statements for the above variables have been left out.

Java also allows shortcuts for some arithmetic expressions:

  age++; // this adds one to the value stored in "age", replacing the original value stored there
  age += 10; // this adds 10 to the value stored in "age"

Text manipulations usually involve "concatenation", or joining of strings. For example:

  String name; // a declaration statement
  name = "Robert"; // an assignment statement, referring "name" to an object that contains a first name
  name += " Burns"; // now a full name is stored in an object referred to by "name"

This assignment is worth 20 points, and consists of 3 exercises. Zero points will be awarded for programs with misspelled filenames, or incorrect case. Zero points will be awarded for programs that do not compile. Partial points will be awarded for programs that are run but do not conform to all specifications, at the discretion of the grader. Be sure to complete both exercises and post the lab1b.jar before midnight of the due date, because there is a 5-point-per-day lateness penalty for late work. Check the course outline for due dates for lab assignments.



EXERCISE 1: My Java Variables (5 points)
Using any code editor or text editor, write the following program and save it as MyJavaVariables.java. But replace the ?? characters with the correct date or your own name, where appropriate (-5 points for not doing this modification). Also, make the other changes that are included in the specification below.
// javac compsci61b/intro/MyJavaVariables.java
// java -ea compsci61b.intro.MyJavaVariables
// jar cf lab1b.jar compsci61b/*
// java -ea -cp lab1b.jar compsci61b.intro.MyJavaVariables

// Programmer: ?? ??
// Assignment: MyJavaVariables.java
// Date: ??/??/2007
// Version: original

package compsci61b.intro; // the folder where this .java file MUST be stored

public class MyJavaVariables // class name MUST match filename
{
  public static void main(String[] argv) // container for statements to be executed by the program
  {
    // whole numbers (exact)
    int i = 1;
    System.out.println("the value of i is [" + i + "]");

    // floating point numbers (imprecise)
    double d = 3.14159;
    System.out.println("the value of d is [" + d + "]");

    // single-character text
    char c = 'X'; // case matters!
    System.out.println("the value of c is [" + c + "]");

    // equivalent forms that look like immutable objects
    Integer iObject = 1;
    System.out.println("the value of iObject is [" + iObject + "]");

    // floating point numbers (imprecise)
    Double dObject = 3.14159;
    System.out.println("the value of dObject is [" + dObject + "]");

    // single-character text
    Character cObject = 'X'; // case matters!
    System.out.println("the value of cObject is [" + cObject + "]");

    // doing math
    i = i + 1;
    i += 1;
    i++;

    i = i - 10;
    i -= 10;

    dObject = d / i; // division
    System.out.println("the value of dObject is now [" + dObject + "]");

    d = d * 10; // multiplication
    System.out.println("the value of d is [" + d + "]");
  }
}

Follow the same detailed specifications that applied to lab 1a's exercise 1, adjusting for the class name. Also, store the files in the same folder that has your lab 1a files, so that when you build the ".jar" file, it contains all the files from both labs 1a and 1b. This will continue with lab 1c, and start over again with lab 2a and all remaining labs which will get placed in a different folder.

Compile, jar, and run. But do not post this version of lab1b.jar -- wait until you complete the remaining exercises.



EXERCISE 2: Your Java Variables (10 points)
Write YourJavaVariables.java in package compsci61b.intro, using exercise 1 as a model. Fully replace the contents of the main container with various declaration, assignment, and output statements of your own design. Here are the detailed specs:

Compile, jar, and run. But do not post this version of lab1b.jar -- wait until you complete the remaining exercise.



EXERCISE 3: A Puzzle For You To Solve (5 points)
Write MyPyramid.java in package compsci61b.intro, using exercise 2 as a model. Arrange the given statements in the correct order and put them in main so that your program will output the triangle:
*
**
***
****
*****
******
*******
********
*********
**********

Each statement may only be used no more than once. Some statements may not be used at all. You may add as many closing curly braces to the while statements as you need. Use ONLY the statements below exactly as they appear, do not modify them or add your own statements (except for closing curly braces).

col += 1;
int col = 0;
int row = 0;
int SIZE = 10;
row += 1;
System.out.print('*');
System.out.println('*');
System.out.println();
while(col <= row) {
while(col < row) {
while (row < SIZE) {
while (row <= SIZE) {

With your files from lab 1a and from exercises 1 and 2 still in the folder, complete exercise 3. Then when you recreate lab1b.jar, the files from both labs' exercises will be in the single ".jar" file.

Post your lab1b.jar file to your student UNIX account for grading and credit.


[ Home | Contact Prof. Burns ]