|
Assignment 03
Task
Get a little more practice with data types, operators, expressions, variables, assignment, and understanding errors.
Textbook: 1.5 (errors); 2.4 - 2.5
Steps
Below are 10 short sections of code. Each one includes one System.out.println statement. For each section, if the code will run successfully, tell me the following things:
- What is printed to the screen?
- What is the data type of the argument (the thing in the parentheses) of the
println method call? (If this argument is an expression, tell me what the data type is of the resulting single value.)
If the code contains an error that will prevent it from compiling or printing normal output, instead tell me the following things:
- Does the error occur at compile time or runtime?
- What is the cause of the error?
- How could the error be fixed?
Here are two example code sections and the appropriate answers:
int answer = 3;
System.out.println("Answer: " + answer);
Prints: "Answer: 3"
Data type: String
int average = 3;
int count = 0;
System.out.println(average / count);
Error: runtime
Cause: cannot divide by 0 (count contains the value 0)
Fix: initialize count to 1 rather than 0.
You should first try to answer these questions by just examining the code. Then, to check your answers, paste each section into a main method, compile it, and run the resulting program.
Questions
-
System.out.println("My age is " + 2008 - 1980);
-
char grade = 'B';
grade++;
System.out.println(grade);
-
int num = 5;
System.out.println(num / 10);
-
int num = 5;
System.out.println(num / 10.0);
-
double num = 5;
System.out.println(num / 10);
-
int num = 5.0;
System.out.println(num / 10);
-
int num = 18;
int pre = ++num;
int post = num++;
System.out.println("Pre: " + pre + ". Post: " + post + ". Num: " + num);
-
String oct;
oct = "Hallow";
oct += "een";
oct += "\b\b";
oct += "'en";
System.out.println(oct);
-
System.out.println("Tis the season " +
"to be jolly.");
-
short a, b = 3, c;
a = c = --b;
a *= ++c;
System.out.println((byte) a);
What to submit
Paste your answers to the questions into the body of an email to me. Do not attach any files. Remember to follow the email submission policies.
Grading [4 points]
- 4 - Questions Answered
- 0.4 points per question (minus penalty for improper submission).
FAQs
- Data type? You mean like "expression" or "variable"?
- No. Variables and expressions are not themselves data types. They
evaluate to or contain a single value, and it is this value that has a
data type associated with it.
Data types are either
one of the 8 primitive data types or else a class name. For this
assignment, valid data types include: byte, short,
int, long, float, double, char, boolean, and String. These are all the
data types we've learned about at this point.
|