Get a little more practice with data types, operators, expressions, variables, assignment, and understanding errors.
Textbook: 1.5 (errors); 2.1 - 2.5
Below are 10 short sections of code. Each one includes one
System.out.println statement. For each section, if the code runs successfully, tell me the following things:
printlnmethod 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 causes a crash at runtime, instead tell me the following things:
Some of these code snippets are examples of bad code (that you should not emulate, but must still be able to read), and their purpose is often not obvious. So ignore any apparent logical errors (such as int math, apparently incorrect output, etc) for now. For this assignment, it only counts as an error if the program doesn't compile or doesn't complete (crashes); if it runs, tell me the value and data type of what is printed.
Here are two example code sections and the appropriate answers:
int answer = 3; System.out.println("Answer: " + answer);
Prints: "Answer: 3"
Data type: Stringint average = 3; int count = 0; System.out.println(average / count);
Cause: cannot divide by 0 (
countcontains 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.
int beers = 99; String song = "Take one down, pass it around: "; song += beers - 1; song += " bottles of beer on the wall."; System.out.println(song);
double f = 1.8; long c = 10; f *= c; f += 32; System.out.println((short) f);
int cipher = 11; char letter = (char) ('z' - cipher); System.out.println(letter);
int num = 10; System.out.println(num / 4.0);
int num = 10.0; System.out.println(num / 4);
double num = 10; System.out.println(num / 4);
int num = 10; System.out.println(num / 4);
int num = 3; int pre = ++num; int post = num++; System.out.println("Pre: " + pre + " Post: " + post + " Num: " + num);
System.out.println('\"I'll \never like this!\" she said.');
long a, b = 1, c; a = c = --b; a %= c++; System.out.println((byte) a);
Save your answers in a plain text file named
UsernameA03.txt. Submit this file to Tamarin.
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. Remember that Java is case-sensitive and that primitive data types are all lowercase.