CS 163/164, Spring 2018
Lab 3 - Variables, Data Types, and Expressions
Tuesday, Jan. 23rd or
Wednesday, Jan. 24th
Objectives of this Lab
- Visit the Piazza bulletin board so you know where to post questions,
- learn about Java variables and expressions,
- understand integer versus floating point math,
- see how the order of precedence affects expressions,
- find out the difference between println, print, and printf, and
- learn how to format output using printf.
Piazza
Your TA will help you navigate to the Piazza website and show you how to post and
answer questions. The link for Piazza is on the syllabus and
here.
Getting Started
Create a new Java Project named R3, and make a class named R3.
Java Variables
Following the instructions below, in order.
- Add declarations of the following variables to the main method:
- Two variables of character type (char) called c0 and c1, initialized to '$' and 'W'.
- Two variables of 8-bit integer type (byte) called b0 and b1, initialized to 15 and 4.
- Two variables of 16-bit integer type (short) called s0 and s1, initialized to 5577 and 1234.
- Two variables of 32-bit integer type (int) called i0 and i1, initialized to 12345 and -99999.
- Two variables of 64-bit integer type (long) called l0 and l1, initalized to 8000000000l and -7000000000l.
- Two variables of 32-bit floating-point type (float) called f0 and f1, initialized to 1.2345f and 66.7788f.
- Two variables of 64-bit floating-point type (double) called d0 and d1, initialized to 0.00001 and 83475.29837.
- Print the following expressions, using System.out.println:
NOTE: The instructor will show you how to copy statements to minimize typing!
- b0 + b1
- (b0 + b1) / 4
- (b0 + b1) / 4.0
- s0 / 1000
- s0 / 1000.0
- s1 % 100
- (i0 - 2345) * 10
- i0 - 2345 * 10
- l1 + i1
- (f0 + f1) / (d0 * d1)
- 0.1 + 0.2 - 0.3
- 6 % 4 + 12 - 3 * (8 + 3) / 2
- Think about the above behavior and be prepared to answer the following questions:
- Explain the difference in the result of (b0 + b1) / 4 and (b0 + b1) / 4.0.
- Explain the difference in the result of s0 / 1000 and s0 / 1000.0.
- Explain the result of the modulo operation in s1 % 100.
- Explain the difference in the result of (i0 - 2345) * 10 and i0 - 2345 * 10.
- Explain the result of 0.1 + 0.2 - 0.3, why is this not zero?
- Can you hand calculate the expression 6 % 4 + 12 - 3 * (8 + 3) / 2 and get the right answer?
- Experiment with different print statements, as follows:
- Increment c0 and c1, then print (c0 + "," + c1) using System.out.println;
- Print ("5577 + 1234 = " + s0 + s1) using System.out.println.
- Print ("5577 + 1234 = %d\n", s0 + s1), using System.out.printf.
- Print ("0.00001 + 83475.29837 = %.2f\n", d0 + d1) using System.out.printf.
- Print ("0.00001 + 83475.29837 = %.5f\n", d0 + d1) using System.out.printf.
- Make sure your R3.java compiles and produces 17 lines of output.
- Show your output to the TA to receive credit for the recitation.