CIS TEST 2 3260

¡Supera tus tareas y exámenes ahora con Quizwiz!

What is the string literal that consists of a single character A?

"A"

Write a character literal representing the digit 1.

'1'

What is a literal for character A?

'A'

What is wrong with the following programs? (a) 1 public class ShowErrors { 2 public static void main(String[] args) { 3 int i = 0; 4 do { 5 System.out.println(i + 4); 6 i++; 7 } 8 while (i < 10) 8 } 9 } (b) 1 public class ShowErrors { 2 public static void main(String[] args) { 3 for (int i = 0; i < 10; i++); 4 System.out.println(i + 4); 5 } 6 }

(a) Line 8: Missing ; at the end of this line. (b) Line 3: The ; at the end of for loop should be removed. for (int i = 0; i < 10; i++);

Rewrite the following conditional expressions using if-else statements. a. score = (x > 10) ? 3 * scale : 4 * scale; b. tax = (income > 10000) ? income * 0.2 : income * 0.17 + 1000; c. System.out.println((number % 3 == 0) ? i : j);

(a) if (x > 10) score = 3 * scale; else score = 4 * scale; (b) if (income > 10000) tax = income * 0.2; else tax = income * 0.17 + 1000; (c) if (number % 3 == 0) System.out.println(i); else System.out.println(j);

a) Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100.

(a) (num > 1) && (num < 100)

What is the output of System.out.print ("ABCD" .indexOf("BC"))?

1

static method

A method invoked from a class name.

Suppose i is an int type variable. Which of the following statements display the character whose Unicode is stored in variable i? A. System.out.println(i); B. System.out.println((char)i); C. System.out.println((int)i); D. System.out.println(i + " ");

B. System.out.println((char)i);

escape character

The backslash \ is called an escape character.

List the precedence order of the Boolean operators. Evaluate the following expressions: true || true && false true && true || false

The precedence order for boolean operators is !, ^, &&, and || true || true && false is true true && true || false is true

Are the following two statements equivalent? (a) if (income <= 10000) tax = income * 0.1; else if (income <= 20000) tax = 1000 + (income - 10000) * 0.15; (b) if (income <= 10000) tax = income * 0.1; else if (income > 10000 && income <= 20000) tax = 1000 + (income - 10000) * 0.15;

YES

Are the following two expressions the same? (a) x % 2 == 0 && x % 3 == 0 (b) x % 6 == 0

Yes

Operator Associativity

determines the order of evaluation for the operators with the same precedence.

Assume x is "ABC" and y is "ABD", what is x.equals(y)?

false

rint(x)

x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double value.

ceil(x)

x is rounded up to its nearest integer. This integer is returned as a double value.

What is y after the following switch statement is executed? Rewrite the code using an if-else statement. x = 3; y = 3; switch (x + 3) { case 6: y = 1; default: y += 1; }

y is 2. x = 3; y = 3; if (x + 3 == 6) { y = 1; } y += 1;

Given a String variable address, write a String expression consisting of the string "http://" concatenated with the variable's String value. So, if the variable refers to "www.turingscraft.com", the value of the expression would be "http://www.turingscraft.com".

"http://" + address

Write a character literal representing a comma.

','

Write an expression that obtains a random integer between 34 and 55. Write an expression that obtains a random integer between 0 and 999. Write an expression that obtains a random number between 5.5 and 55.5.

(a) 34 + (int)(Math.random() * (55 - 34)) (b) (int)(Math.random() * 1000) (c) 5.5 + (Math.random() * (55.5 - 5.5))

How many times are the following loop bodies repeated? What is the output of each loop? (a) int i = 1; while (i < 10) if (i % 2 == 0) System.out.println(i); (b) int i = 1; while (i < 10) if (i % 2 == 0) System.out.println(i++); (c) int i = 1; while (i < 10) if ((i++) % 2 == 0) System.out.println(i);

(a) Infinite number of times. (b) Infinite number of times. (c) The loop body is executed nine times. The output is 3, 5, 7, 9 on separate lines.

Evaluate the following method calls: (a) Math.sqrt(4) (b) Math.sin(2 * Math.PI) (c) Math.cos(2 * Math.PI) (d) Math.pow(2, 2) (e) Math.log(Math.E) (f) Math.exp(1) (g) Math.max(2, Math.min(3, 4)) (h) Math.rint(-2.5) (i) Math.ceil(-2.5) (j) Math.floor(-2.5) (k) Math.round(-2.5f) (l) Math.round(-2.5) (m) Math.rint(2.5) (n) Math.ceil(2.5) (o) Math.floor(2.5) (p) Math.round(2.5f) (q) Math.round(2.5) (r) Math.round(Math.abs(-2.5))

(a) Math.sqrt(4) = 2.0 (b) Math.sin(2*Math.PI) = 0 (c) Math.cos(2*Math.PI) = 1 (d) Math.pow(2, 2) = 4.0 (e) Math.log(Math.E) = 1.0 (f) Math.exp(1) = 2.718 (g) Math.max(2, Math.min(3, 4)) = 3 (h) Math.rint(-2.5) = -2.0 (i) Math.ceil(-2.5) = -2.0 (j) Math.floor(-2.5) = -3.0 (k) Math.round(-2.5f) = -2 (l) Math.round(-2.5) = -2 (m) Math.rint(2.5) = 2.0 (n) Math.ceil(2.5) = 3.0 (o) Math.floor(2.5) = 2.0 (p) Math.round(2.5f) = 3 (q) Math.round(2.5) = 3 (r) Math.round(Math.abs(-2.5)) = 3

Show the output of the following statements. (a) System.out.printf("amount is %f %e\n", 32.32, 32.32); (b) System.out.printf("amount is %5.2f%% %5.4e\n", 32.327, 32.32); (c) System.out.printf("%6b\n", (1 > 2)); (d) System.out.printf("%6s\n", "Java"); (e) System.out.printf("%-6b%s\n", (1 > 2), "Java"); (f) System.out.printf("%6b%-8s\n", (1 > 2), "Java"); (g) System.out.printf("%,5d %,6.1f\n", 312342, 315562.932); (h) System.out.printf("%05d %06.1f\n", 32, 32.32);

(a) amount is 32.320000 3.233000e+01 (b) amount is 32.33% 3.2330e+01 (c) *false // * denote a space (d) **Java // * denote a space (e) false*Java (f) *falseJava**** (g) 312,342 315,562.9 (h) 00032 0032.3

Let s1 be " Welcome " and s2 be " welcome ". Write the code for the following statements: a. Check whether s1 is equal to s2 and assign the result to a Boolean variable isEqual. b. Check whether s1 is equal to s2, ignoring case, and assign the result to a Boolean variable isEqual. c. Compare s1 with s2 and assign the result to an int variable x. d. Compare s1 with s2, ignoring case, and assign the result to an int variable x. e. Check whether s1 has the prefix AAA and assign the result to a Boolean variable b. f. Check whether s1 has the suffix AAA and assign the result to a Boolean variable b. g. Assign the length of s1 to an int variable x. h. Assign the first character of s1 to a char variable x. i. Create a new string s3 that combines s1 with s2. j. Create a substring of s1 starting from index 1. k. Create a substring of s1 from index 1 to index 4. l. Create a new string s3 that converts s1 to lowercase. m. Create a new string s3 that converts s1 to uppercase. n. Create a new string s3 that trims whitespaces on both ends of s1. o. Assign the index of the first occurrence of the character e in s1 to an int variable x. p. Assign the index of the last occurrence of the string abc in s1 to an int variable x.

(a) boolean isEqual = s1.equals(s2); (b) boolean isEqual = s1.equalsIgnoreCase(s2); (c) int x = s1.compareTo(s2); (d) int x = s1.compareToIgnoreCase(s2); (e) boolean b = s1.startsWith("AAA"); (f) boolean b = s1.endsWith("AAA"); (g) int x = s1.length(); (h) char x = s1.charAt(0); (i) String s3 = s1 + s2; (j) String s3 = s1.substring(1); (k) String s3 = s1.substring(1, 5); (l) String s3 = s1.toLowerCase(); (m) String s3 = s1.toUpperCase(); (n) String s3 = s1.trim(); (o) int x = s1.indexOf('e'); (p) int x = s1.lastIndexOf("abc");

Count the number of iterations in the following loops. (a) int count = 0; while (count < n) { count++; } (b) for (int count = 0; count <= n; count++) { } (c) int count = 5; while (count < n) { count++; } (d) int count = 5; while (count < n) { count = count + 3; }

(a) n times (b) n+1 times (b) n-5 times (d) The ceiling of (n-5)/3 times

What is wrong in the following statements? (a) System.out.printf("%5d %d\n", 1, 2, 3); (b) System.out.printf("%5d %f\n", 1); (c) System.out.printf("%5d %f\n", 1, 2); (d) System.out.printf("%.2f\n%0.3f\n", 1.23456, 2.34); (e) System.out.printf("%08s\n", "Java");

(a) the last item 3 does not have any specifier. (b) There is not enough items. (c) The data for %f must a floating-point value. (d) %0.3f is wrong. Width cannot be zero. (e) %08s is wrong. 0 should be removed.

(b) Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100 or the number is negative.

(b) (num > 1) && (num < 100) || num < 0

(b) Write a Boolean expression for |x - 5| > 4.5.

(b) (x - 5) > 4.5 || (x - 5) < -4.5

Write one statement to return the number of digits in a double value d.

(d + "").length()

Write one statement to return the number of digits in an integer i.

(i + "").length()

Write conditional expression that returns -1 or 1 randomly.

(int)(Math.random() * 2) == 0 ? -1 : 1;

(a) Write a Boolean expression for |x - 5| < 4.5.

(x - 5) < 4.5 && (x - 5) > -4.5

Suppose, when you run the following program, you enter the input 2 3 6 from the console. What is the output? public class Test { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); double x = input.nextDouble(); double y = input.nextDouble(); double z = input.nextDouble(); System.out.println("(x < y && y < z) is " + (x < y && y < z)); System.out.println("(x < y || y < z) is " + (x < y || y < z)); System.out.println("!(x < y) is " + !(x < y)); System.out.println("(x + y < z) is " + (x + y < z)); System.out.println("(x + y > z) is " + (x + y > z));

(x < y && y < z) is true (x < y || y < z) is true !(x < y) is false (x + y < z) is true (x + y > z) is false

Four int variables, x1, x2, y1, and y2, have been declared and been given values. Write an expression whose value is the difference between the larger of x1 and x2 and the smaller of y1 and y2.

(x1 > x2 ? x1 : x2) - (y1 < y2 ? y1 : y2)

Given the int variables yearsWithCompany and department, write an expression that evaluates to true if yearsWithCompany is less than 5 and department is not equal to 99.

(yearsWithCompany < 5 && department != 99)

Evaluate the following expressions (write a program to verify your results): 1 + "Welcome " + 1 + 1 1 + "Welcome " + (1 + 1) 1 + "Welcome " + ('\u0001' + 1) 1 + "Welcome " + 'a' + 1

1 + "Welcome " + 1 + 1 is 1Welcome 11. 1 + "Welcome " + (1 + 1) is 1Welcome 2. 1 + "Welcome " + ('\u0001' + 1) is 1Welcome 2 1 + "Welcome " + 'a' + 1 is 1Welcome a1

If you run Listing 4.3 GuessBirthday.java with input 1 for Set1, Set3, and Set4 and 0 for Set2 and Set5, what will be the birthday?

13

What is the output of the following code? for (int i = 1; i < 10; i += 2) { System.out.printf("%1d", i); }

13579

How many times is the following loop executed? for (int count = 1; count < 5; count += 3)

2

How many days in the February of a leap year? Which of the following is a leap year? 500, 1000, 2000, 2016, and 2020?

29 days. 500, 1000 are not leap years. 2000, 2016, and 2020 are leap years.

What is the output of System.out.printf("%-6.2f%-6.2f", 3.503, 4.355)?

3.50 4.36

What is the output of System.out.printf("%2d%6.2f", 32, 32.5)?

32 32.50

What is the output of System.out.printf("%2d%.2f", 32, 32.5)?

3232.50

How many times is the following loop executed? int count = 1; do { count += 3; } while (count < 5);

5

What is the output of System.out.print ("ABCDABC". lastIndexOf("BC"))?

5

What is Math.log(Math.exp(5.5))? What is Math.exp(Math.log(5.5))? What is Math.asin(Math.sin(Math.PI / 6))? What is Math.sin(Math.asin(Math.PI / 6))?

5.5 5.5 0.5235987755982988 0.5235987755982988

Write a literal representing the character whose unicode value is 65.

65

What is count after the loop is finished? int count = 1; do { count += 3; } while (count < 5);

7

Unicode

A code system for international characters managed by the Unicode Consortium. Java supports Unicode.

format specifier

A format specifier specifies how an item should be displayed. An item may be a numeric value, a character, a Boolean value, or a string.

instance method

A method that must be invoked from a specific object.

escape sequence

A special notation, consisting of a backslash (\) followed by a character or a combination of digits.

Which of the following are valid specifiers for the printf statement? A. %4c B. %10b C. %6d D. %8.2d E. %10.2e

A. %4c B. %10b C. %6d E. %10.2e

An int variable can hold __________. A. 'x' B. 120 C. 120.0 D. "x" E. "120"

A. 'x' B. 120

Which of the following statements are true? A. (x > 0 && x < 10) is same as ((x > 0) && (x < 10)) B. (x > 0 || x < 10) is same as ((x > 0) || (x < 10)) C. (x > 0 || x < 10 && y < 0) is same as (x > 0 || (x < 10 && y < 0)) D. (x > 0 || x < 10 && y < 0) is same as ((x > 0 || x < 10) && y < 0)

A. (x > 0 && x < 10) is same as ((x > 0) && (x < 10)) B. (x > 0 || x < 10) is same as ((x > 0) || (x < 10)) C. (x > 0 || x < 10 && y < 0) is same as (x > 0 || (x < 10 && y < 0))

What is y after the following statement is executed? x = 0; y = (x > 0) ? 10 : -10; A. -10 B. 0 C. 10 D. 20 E. Illegal expression

A. -10

What is sum after the following loop terminates? int sum = 0; int item = 0; do { item++; if (sum >= 4)continue; sum += item; } while (item < 5); A. 6 B. 7 C. 8 D. 9 E. 10

A. 6

Note that the Unicode for character A is 65. The expression 'A' + 1 evaluates to ________. A. 66 B. B C. A1 D. Illegal expression

A. 66

To obtain the arc sine of 0.5, use _______. A. Math.asin(0.5) B. Math.asin(Math.toDegrees(0.5)) C. Math.sin(Math.toRadians(0.5)) D. Math.sin(0.5)

A. Math.asin(0.5)

Which of the following should be defined as a void method? A. Write a method that prints integers from 1 to 100. B. Write a method that returns a random integer from 1 to 100. C. Write a method that checks whether an integer is from 1 to 100. D. Write a method that converts an uppercase letter to lowercase.

A. Write a method that prints integers from 1 to 100.

Do the following two statements in (I) and (II) result in the same value in sum? (I): for (int i = 0; i < 10; ++i) { sum += i; } (II):for (int i = 0; i < 10; i++) { sum += i; } A. Yes B. No

A. Yes

To add 0.01 + 0.02 + ... + 1.00, what order should you use to add the numbers to get better accuracy? A. add 0.01, 0.02, ..., 1.00 in this order to a sum variable whose initial value is 0. B. add 1.00, 0.99, 0.98, ..., 0.02, 0.01 in this order to a sum variable whose initial value is 0.

A. add 0.01, 0.02, ..., 1.00 in this order to a sum variable whose initial value is 0.

Analyze the following code.int count = 0;while (count < 100) {// Point ASystem.out.println("Welcome to Java!");count++;// Point B}// Point C A. count < 100 is always true at Point A B. count < 100 is always true at Point B C. count < 100 is always false at Point B D. count < 100 is always true at Point C E. count < 100 is always false at Point C

A. count < 100 is always true at Point A E. count < 100 is always false at Point C

To check if a string s contains the suffix "Java", you may write A. if (s.endsWith("Java")) ... B. if (s.lastIndexOf("Java") >= 0) ... C. if (s.substring(s.length() - 4).equals("Java")) ... D. if (s.substring(s.length() - 5).equals("Java")) ... E. if (s.charAt(s.length() - 4) == 'J' && s.charAt(s.length() - 3) == 'a' && s.charAt(s.length() - 2) == 'v' && s.charAt(s.length() - 1) == 'a') ...

A. if (s.endsWith("Java")) ... C. if (s.substring(s.length() - 4).equals("Java")) ... E. if (s.charAt(s.length() - 4) == 'J' && s.charAt(s.length() - 3) == 'a' && s.charAt(s.length() - 2) == 'v' && s.charAt(s.length() - 1) == 'a') ...

To check if a string s contains the prefix "Java", you may write A. if (s.startsWith("Java")) ... B. if (s.indexOf("Java") == 0) ... C. if (s.substring(0, 4).equals("Java")) ... D. if (s.charAt(0) == 'J' && s.charAt(1) == 'a' && s.charAt(2) == 'v' && s.charAt(3) == 'a') ...

A. if (s.startsWith("Java")) ... B. if (s.indexOf("Java") == 0) ... C. if (s.substring(0, 4).equals("Java")) ... D. if (s.charAt(0) == 'J' && s.charAt(1) == 'a' && s.charAt(2) == 'v' && s.charAt(3) == 'a') ...

Suppose s1 and s2 are two strings. What is the result of the following code? s1.equals(s2) == s2.equals(s1) A. true B. false

A. true

What is the value of the following expression? true || true && false A. true B. false

A. true

Suppose your method does not return any value, which of the following keywords can be used as a return type? A. void B. int C. double D. public E. None of the above

A. void

Which of the Boolean expressions below is incorrect? A. (true) && (3 => 4) B. !(x > 0) && (x > 0) C. (x > 0) || (x < 0) D. (x != 0) || (x = 0) E. (-10 < x < 0)

A.(true) && (3 => 4) D.(x != 0) || (x = 0) E. (-10 < x < 0)

What is the output of System.out.print ("ABC". substring(0, 2))?

AB

What is the return value of "SELECT".substring(0, 5)? A. "SELECT" B. "SELEC" C. "SELE" D. "ELECT"

B. "SELEC"

Which of the following is the correct expression that evaluates to true if the number x is between 1 and 100 or the number is negative? A. 1 < x < 100 && x < 0 B. ((x < 100) && (x > 1)) || (x < 0) C. ((x < 100) && (x > 1)) && (x < 0) D. (1 > x > 100) || (x < 0)

B. ((x < 100) && (x > 1)) || (x < 0)

'3' - '2' + 'm' / 'n' is ______. A. 0 B. 1 C. 2 D. 3

B. 1

What is y after the following for loop statement is executed?int y = 0; for (int i = 0; i < 10; ++i) { y += 1;} A. 9 B. 10 C. 11 D. 12

B. 10

What is y after the following switch statement is executed? int x = 3; int y = 4; switch (x + 3) { case 6: y = 0; case 7: y = 1; default: y += 1; } A. 1 B. 2 C. 3 D. 4 E. 0

B. 2

To obtain the sine of 35 degrees, use _______. A. Math.sin(35) B. Math.sin(Math.toRadians(35)) C. Math.sin(Math.toDegrees(35)) D. Math.sin(Math.toRadian(35)) E. Math.sin(Math.toDegree(35))

B. Math.sin(Math.toRadians(35))

Does the method call in the following method cause compile errors? public static void main(String[] args) { Math.pow(2, 4);} A. Yes B. No

B. No

Does the return statement in the following method cause compile errors? public static void main(String[] args) { int max = 0; if (max != 0) System.out.println(max); else return;} A. Yes B. No

B. No

Will System.out.println((char)4) display 4? A. Yes B. No

B. No

Will the following program terminate? int balance = 10; while (true) { if (balance < 9) continue; balance = balance - 9;} A. Yes B. No

B. No

What is the output of the following code? boolean even = false; System.out.println((even ? "true" : "false")); A. true B. false C. nothing D. true false

B. false

What is the output after the following loop terminates?int number = 25;int i;boolean isPrime = true;for (i = 2; i < number; i++) {if (number % i == 0) {isPrime = false;break;}}System.out.println("i is " + i + " isPrime is " + isPrime); A. i is 5 isPrime is true B. i is 5 isPrime is false C. i is 6 isPrime is true D. i is 6 isPrime is false

B. i is 5 isPrime is false

The signature of a method consists of ____________. A. method name B. method name and parameter list C. return type, method name, and parameter list D. parameter list

B. method name and parameter list

What is the number of iterations in the following loop?for (int i = 1; i <= n; i++) {// iteration} A. 2*n B. n C. n - 1 D. n + 1

B. n

Arguments to methods always appear within __________. A. brackets B. parentheses C. curly braces D. quotation marks

B. parentheses

Assume x = 4 and y = 5, which of the following is true? A. !(x == 4) ^ y != 5 B. x != 4 ^ y == 5 C. x == 5 ^ y == 4 D. x != 5 ^ y != 4

B. x != 4 ^ y == 5

Assume x = 4 and y = 5, which of the following is true? A. x < 5 && y < 5 B. x < 5 || y < 5 C. x > 5 && y > 5 D. x > 5 || y > 5

B. x < 5 || y < 5

Evaluate the following expressions: 2 * 2 - 3 > 2 && 4 - 2 > 5 2 * 2 - 3 > 2 || 4 - 2 > 5

Both are false

The order of the precedence (from high to low) of the operators binary +, *, &&, ||, ^ is: A. &&, ||, ^, *, + B. *, +, &&, ||, ^ C. *, +, ^, &&, || D. *, +, ^, ||, && E. ^, ||, &&, *, +

C. *, +, ^, &&, ||

What is the value of balance after the following code is executed?int balance = 10;while (balance >= 1) {if (balance < 9)break;balance = balance - 9;} A. -1 B. 0 C. 1 D. 2

C. 1

How many times will the following code print "Welcome to Java"?int count = 0;do {System.out.println("Welcome to Java");count++;} while (count < 10); A. 8 B. 9 C. 10 D. 11 E. 0

C. 10

How many times will the following code print "Welcome to Java"?int count = 0;do {System.out.println("Welcome to Java");} while (++count < 10); A. 8 B. 9 C. 10 D. 11 E. 0

C. 10

How many times will the following code print "Welcome to Java"?int count = 0;while (count < 10) {System.out.println("Welcome to Java");count++;} A. 8 B. 9 C. 10 D. 11 E. 0

C. 10

How many times will the following code print "Welcome to Java"?int count = 0;while (count++ < 10) {System.out.println("Welcome to Java");} A. 8 B. 9 C. 10 D. 11 E. 0

C. 10

What is the value in count after the following loop is executed?int count = 0;do {System.out.println("Welcome to Java");} while (count++ < 9);System.out.println(count); A. 8 B. 9 C. 10 D. 11 E. 0

C. 10

The statement System.out.printf("%5d", 123456) outputs ___________. A. 12345 B. 23456 C. 123456 D. 12345.6

C. 123456

What is Math.ceil(3.6)? A. 3.0 B. 3 C. 4.0 D. 5.0

C. 4.0

What is Math.rint(3.6)? A. 3.0 B. 3 C. 4.0 D. 5.0

C. 4.0

Note that the Unicode for character A is 65. The expression "A" + 1 evaluates to ________. A. 66 B. B C. A1 D. Illegal expression

C. A1

The expression "Java " + 1 + 2 + 3 evaluates to ________. A. Java123 B. Java6 C. Java 123 D. java 123 E. Illegal expression

C. Java 123

Analyze the following code: import java.util.Scanner; public class Test { public static void main(String[] args) { int sum = 0; for (int i = 0; i < 100000; i++) { Scanner input = new Scanner(System.in); sum += input.nextInt(); } } } A. The program does not compile because the Scanner input = new Scanner(System.in); statement is inside the loop. B. The program compiles, but does not run because the Scanner input = new Scanner(System.in); statement is inside the loop. C. The program compiles and runs, but it is not efficient and unnecessary to execute the Scanner input = new Scanner(System.in); statement inside the loop. You should move the statement before the loop. D. The program compiles, but does not run because there is not prompting message for entering the input.

C. The program compiles and runs, but it is not efficient and unnecessary to execute the Scanner input = new Scanner(System.in); statement inside the loop. You should move the statement before the loop.

Analyze the following code: public class Test { public static void main (String args[]) { int i = 0;for (i = 0; i < 10; i++); System.out.println(i + 4);} } A. The program has a compile error because of the semicolon (;) on the for loop line. B. The program compiles despite the semicolon (;) on the for loop line, and displays 4. C. The program compiles despite the semicolon (;) on the for loop line, and displays 14. D. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4);

C. The program compiles despite the semicolon (;) on the for loop line, and displays 14. D. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4);

Analyze the following fragment: double sum = 0; double d = 0; while (d != 10.0) { d += 0.1;sum += sum + d;} A. The program does not compile because sum and d are declared double, but assigned with integer value 0. B. The program never stops because d is always 0.1 inside the loop. C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers. D. After the loop, sum is 0 + 0.1 + 0.2 + 0.3 + ... + 1.9

C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers.

Analyze the following program fragment: int x; double d = 1.5; switch (d) { case 1.0: x = 1; case 1.5: x = 2; case 2.0: x = 3; } A. The program has a compile error because the required break statement is missing in the switch statement. B. The program has a compile error because the required default case is missing in the switch statement. C. The switch control variable cannot be double. D. No errors.

C. The switch control variable cannot be double

Each time a method is invoked, the system stores parameters and local variables in an area of memory, known as _______, which stores elements in last-in first-out fashion. A. a heap B. storage area C. a stack D. an array

C. a stack

Suppose x is a char variable with a value 'b'. What is the output of the statement System.out.println(++x)? A. a B. b C. c D. d

C. c

Analyze the following code: int i = 3434; double d = 3434; System.out.printf("%5.1f %5.1f", i, d); A. The code compiles and runs fine to display 3434.0 3434.0. B. The code compiles and runs fine to display 3434 3434.0. C. i is an integer, but the format specifier %5.1f specifies a format for double value. The code has an error.

C. i is an integer, but the format specifier %5.1f specifies a format for double value. The code has an error.

What is the number of iterations in the following loop? for (int i = 1; i < n; i++) { // iteration} A. 2*n B. n C. n - 1 D. n + 1

C. n - 1

All Java applications must have a method __________. A. public static Main(String[] args) B. public static Main(String args[]) C. public static void main(String[] args) D. public void main(String[] args) E. public static main(String[] args)

C. public static void main(String[] args)

What is y displayed in the following code? public class Test1 { public static void main(String[] args) { int x = 1; int y = x = x + 1; System.out.println("y is " + y); } } A. y is 0. B. y is 1 because x is assigned to y first. C. y is 2 because x + 1 is assigned to x and then x is assigned to y. D. The program has a compile error since x is redeclared in the statement int y = x = x + 1.

C. y is 2 because x + 1 is assigned to x and then x is assigned to y.

What is Math.round(3.6)? A. 3.0 B. 3 C. 4 D. 4.0

C.4

What is the output of System.out.print ("ABCD". substring(2))?

CD

If you enter a lowercase letter such as b, the program in Listing 4.4 displays B is 11. Revise the code so to display b is 11.

Change ch in lines 20, 24, 27 to hexString.charAt(0).

Write an expression that tests whether a character ch is a letter or a digit.

Character.isLetterOrDigit(ch)

Write an expression that returns a lowercase letter for a character ch.

Character.toLowerCase(ch)

Which of the following is the correct expression of character 4? A. 4 B. "4" C. '\0004' D. '4'

D. '4'

The statement System.out.printf("%10s", 123456) outputs ___________. (Note: * represents a space) A. 123456**** B. 23456***** C. 12345***** D. ****123456

D. ****123456

"AbA".compareToIgnoreCase("abC") returns ___________. A. 1 B. 2 C. -1 D. -2 E. 0

D. -2

The following loop displays _______________. for (int i = 1; i <= 10; i++) {System.out.print(i + " "); i++; } The correct answer is D. A. 1 2 3 4 5 6 7 8 9 B. 1 2 3 4 5 6 7 8 9 10 C. 1 2 3 4 5 D. 1 3 5 7 9 E. 2 4 6 8 10

D. 1 3 5 7 9

The statement System.out.printf("%3.1e", 1234.56) outputs ___________. A. 0.1e+04 B. 0.123456e+04 C. 0.123e+04 D. 1.2e+03 E. 1.23+03

D. 1.2e+03

How many times will the following code print "Welcome to Java"? int count = 0; do { System.out.println ("Welcome to Java");} while (count++ < 10); A. 8 B. 9 C. 10 D. 11 E. 0

D. 11

The __________ method parses a string s to a double value. A. double.parseDouble(s); B. Double.parsedouble(s); C. double.parse(s); D. Double.parseDouble(s);

D. Double.parseDouble(s);

Analyze the following code. double sum = 0; for (double d = 0; d < 10; sum += sum + d) { d += 0.1;} A. The program has a syntax error because the adjustment statement is incorrect in the for loop. B. The program has a syntax error because the control variable in the for loop cannot be of the double type. C. The program compiles but does not stop because d would always be less than 10. D. The program compiles and runs fine.

D. The program compiles and runs fine.

Analyze the following statement: double sum = 0; for (double d = 0; d < 10;) { d += 0.1;sum += sum + d;} A. The program has a compile error because the adjustment is missing in the for loop. B. The program has a compile error because the control variable in the for loop cannot be of the double type. C. The program runs in an infinite loop because d < 10 would always be true. D. The program compiles and runs fine.

D. The program compiles and runs fine.

You should fill in the blank in the following code with ______________. public class Test {public static void main(String[] args) {System.out.print("The grade is " + getGrade(78.5)); System.out.print("\nThe grade is " + getGrade(59.5));} public static _________ getGrade(double score) {if (score >= 90.0) return 'A'; else if (score >= 80.0) return 'B'; else if (score >= 70.0) return 'C'; else if (score >= 60.0) return 'D'; elsereturn 'F';}} A. int B. double C. boolean D. char E. void

D. char

Suppose the input for number is 9. What is the output from running the following program? import java.util.Scanner;public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int number = input.nextInt(); int i; boolean isPrime = true; for (i = 2; i < number && isPrime; i++) { if (number % i == 0) { isPrime = false;} } System.out.println("i is " + i); if(isPrime) System.out.println(number + " is prime"); else System.out.println(number + " is not prime");}} A. i is 3 followed by 9 is prime B. i is 3 followed by 9 is not prime C. i is 4 followed by 9 is prime D. i is 4 followed by 9 is not prime

D. i is 4 followed by 9 is not prime

What is the output after the following loop terminates?int number = 25;int i;boolean isPrime = true;for (i = 2; i < number && isPrime; i++) {if (number % i == 0) {isPrime = false;}}System.out.println("i is " + i + " isPrime is " + isPrime); A. i is 5 isPrime is true B. i is 5 isPrime is false C. i is 6 isPrime is true D. i is 6 isPrime is false

D. i is 6 isPrime is false

Assume x = 4, which of the following is true? A. !(x == 4) B. x != 4 C. x == 5 D. x != 5

D. x != 5

dangling else ambiguity

Describes a common mistake where an else clause is mismatch to an if clause.

The statement System.out.printf("%3.1f", 1234.56) outputs ___________. A. 123.4 B. 123.5 C. 1234.5 D. 1234.56 E. 1234.6

E. 1234.6

Which of the following operators are right-associative. A. * B. + (binary +) C. % D. && E. =

E. =

Which of the following loops prints "Welcome to Java" 10 times? A: for (int count = 1; count <= 10; count++) {System.out.println("Welcome to Java");} B: for (int count = 0; count < 10; count++) {System.out.println("Welcome to Java");} C: for (int count = 1; count < 10; count++) {System.out.println("Welcome to Java");} D: for (int count = 0; count <= 10; count++) {System.out.println("Welcome to Java");} A. BD B. ABC C. AC D. BC E. AB

E. AB

Analyze the following code fragments that assign a boolean value to the variable even. Code 1: if (number % 2 == 0) even = true; else even = false; Code 2: even = (number % 2 == 0) ? true: false; Code 3: even = number % 2 == 0; A. Code 2 has a compile error, because you cannot have true and false literals in the conditional expression. B. Code 3 has a compile error, because you attempt to assign number to even. C. All three are correct, but Code 1 is preferred. D. All three are correct, but Code 2 is preferred. E. All three are correct, but Code 3 is preferred.

E. All three are correct, but Code 3 is preferred.

Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100? A: double sum = 0; for (int i = 1; i <= 99; i++) { sum = i / (i + 1); } System.out.println("Sum is " + sum); B: double sum = 0; for (int i = 1; i < 99; i++) { sum += i / (i + 1); } System.out.println("Sum is " + sum); C: double sum = 0; for (int i = 1; i <= 99; i++) { sum += 1.0 * i / (i + 1); } System.out.println("Sum is " + sum); D: double sum = 0; for (int i = 1; i <= 99; i++) { sum += i / (i + 1.0); } System.out.println("Sum is " + sum); E: double sum = 0; for (int i = 1; i < 99; i++) { sum += i / (i + 1.0); } System.out.println("Sum is " + sum); A. BCD B. ABCD C. B D. CDE E. CD

E. CD

What balance after the following code is executed?int balance = 10;while (balance >= 1) {if (balance < 9)continue;balance = balance - 9;} A. -1 B. 0 C. 1 D. 2 E. The loop does not end

E. The loop does not end

The for loop in (a) is converted into the while loop in (b). What is wrong? Correct it. (a) int sum = 0; for (int i = 0; i < 4; i++) { if (i % 3 == 0) continue; sum += i; } (b) int i = 0, sum = 0; while (i < 4) { if (i % 3 == 0) continue; sum += i; i++; }

If a continue statement is executed inside a for loop, the rest of the iteration is skipped, then the action-after-each-iteration is performed and the loop-continuation-condition is checked. If a continue statement is executed inside a while loop, the rest of the iteration is skipped, then the loop-continuation-condition is checked. Here is the fix: int i = 0, sum = 0; while (i < 4) { if (i % 3 == 0) { i++; continue; } sum += i; i++; }

What is the value of the expression x >= 50 && x <= 100 if x is 45, 67, or 101?

If x is 45, the expression is false. If x is 67, the expression is true. If x is 101, the expression is false.

The __________ method parses a string s to an int value. A. integer.parseInt(s); B. Integer.parseInt(s); C. integer.parseInteger(s); D. Integer.parseInteger(s);

Integer.parseInt(s);

What happens if you enter an integer as 05?

It will be the same as entering 5.

Identify and fix the errors in the following code: 1 public class Test { 2 public void main(String[] args) { 3 for (int i = 0; i < 10; i++); 4 sum += i; 5 6 if (i < j); 7 System.out.println(i) 8 else 9 System.out.println(j); 10 11 while (j < 10); 12 { 13 j++; 14 } 15 16 do { 17 j++; 18 } while (j < 10) 19 } 20 }

Line 2: missing static. Line 3: The semicolon (;) at the end of the for loop heading should be removed. Line 4: sum not defined. Line 6: the semicolon (;) at the end of the if statement should be removed.Line 6: j not defined. Line 7: Missing a semicolon for the first println statement.Line 11: The semicolon (;) at the end of the while heading should be removed. Line 18: Missing a semicolon at the end of the do-while loop.

The Math class provides a static method, max, that accepts two int arguments and returns the value of the larger one. Two int variables, population1 and population2, have already been declared and initialized. Write an expression (not a statement!) whose value is the larger of population1 and population2 by calling max.

Math.max(population1, population2)

If a right triangle has sides of length a, b and c and if c is the largest, then it is called the hypotenuse and its length is the square root of the sum of the squares of the lengths of the shorter sides (a and b). Assume that variables a and b have been declared as doubles and that a and b contain the lengths of the shorter sides of a right triangle: write an expression for the length of the hypotenuse.

Math.sqrt(a * a + b * b)

If a variable is declared in a for loop control, can it be used after the loop exits?

No. The scope of the variable is inside the loop.

encoding

Representing a character using a binary code.

round(x)

Returns (int)Math.floor (x + 0.5) if x is a float and returns (long)Math.floor (x + 0.5) if x is a double.

concat(s1)

Returns a new string that concatenates this string with string s1.

toLowerCase()

Returns a new string with all letters in lowercase

toUpperCase()

Returns a new string with all letters in uppercase.

trim()

Returns a new string with whitespace characters trimmed on both sides.

compareTo(s1)

Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1.

charAt(index)

Returns the character at the specified index from this string.

toLowerCase(ch)

Returns the lowercase of the specified character.

length()

Returns the number of characters in this string.

toUpperCase(ch)

Returns the uppercase of the specified character.

substring(beginIndex, endIndex)

Returns this string's substring that begins at the specified beginIndex and extends to the character at index endIndex - 1, as shown in Figure 4.2. Note that the character at endIndex is not part of the substring.

substring(beginIndex)

Returns this string's substring that begins with the character at the specified beginIndex and extends to the end of the string,

contains(s1)

Returns true if s1 is a substring in this string.s(

isDigit(ch)

Returns true if the specified character is a digit.

isLetterOrDigit(ch)

Returns true if the specified character is a letter or digit.

isLetter(ch)

Returns true if the specified character is a letter.

isLowerCase(ch)

Returns true if the specified character is a lowercase letter.

isUpperCase(ch)

Returns true if the specified character is an uppercase letter.

endsWith(suffix)

Returns true if this string ends with the specified suffix.

equals(s1)

Returns true if this string is equal to string s1.

equalsIgnoreCase(s1)

Returns true if this string is equal to string s1; it is case insensitive.

startsWith(prefix)

Returns true if this string starts with the specified prefix.

compareToIgnoreCase(s1)

Same as compareTo except that the comparison is case insensitive.

Do the following two loops result in the same value in sum? (a) for (int i = 0; i < 10; ++i) { sum += i; } (b) for (int i = 0; i < 10; i++) { sum += i; }

Same. When the i++ and ++i are used in isolation, their effects are same.

Suppose that, when you run the following program, you enter the input 2 3 6 from the console. What is the output? public class Test { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); double x = input.nextDouble(); double y = input.nextDouble(); double z = input.nextDouble(); System.out.println((x < y && y < z) ? "sorted" : "not sorted"); } }

Sorted

Suppose that s1 and s2 are two strings. Which of the following statements or expressions are incorrect? String s = "Welcome to Java"; String s3 = s1 + s2; String s3 = s1 - s2; s1 == s2; s1 >= s2; s1.compareTo(s2); int i = s1.length(); char c = s1(0); char c = s1.charAt(s1.length());

String s = "Welcome to Java"; Answer: Correct String s3 = s1 + s2; Answer: Correct String s3 = s1 - s2; Answer: Incorrect s1 == s2 Answer: Correct s1 >= s2 Answer: Incorrect s1.compareTo(s2); Answer: Correct int i = s1.length(); Answer: Correct char c = s1(0); Answer: Incorrect char c = s1.charAt(s1.length()); Answer: Incorrect : it's out of bounds, even if the preceding problem is fixed.

There are two String variables, s1 and s2, that have already been declared and initialized. Write some code that exchanges their values. Declare any other variables as necessary.

String x = s1; s1 = s2; s2 = x;

Suppose s is a string with the value "java". What will be assigned to x if you execute the following code? char x = s.charAt(4); A. 'a' B. 'v' Suppose s is a string with the value "java". What will be assigned to x if you execute the following code? char x = s.charAt(4); A. 'a' B. 'v' C. Nothing will be assigned to x, because the execution causes the runtime error StringIndexOutofBoundsException.

Suppose s is a string with the value "java". What will be assigned to x if you execute the following code? char x = s.charAt(4); A. 'a' B. 'v' C. Nothing will be assigned to x, because the execution causes the runtime error StringIndexOutofBoundsException.

What data types are required for a switch variable? If the keyword break is not used after a case is processed, what is the next statement to be executed? Can you convert a switch statement to an equivalent if statement, or vice versa? What are the advantages of using a switch statement?

Switch variables must be of char, byte, short, int, or String types. If a break statement is not used, the next case statement is performed. You can always convert a switch statement to an equivalent if statement, but not an if statement to a switch statement. The use of the switch statement can improve readability of the program in some cases. The compiled code for the switch statement is also more efficient than its corresponding if statement.

The __________ method immediately terminates the program. A. System.terminate(0); B. System.halt(0); C. System.exit(0); D. System.quit(0); E. System.stop(0);

System.exit(0);

Show the output of the following statements (write a program to verify your results): System.out.println("1" + 1); System.out.println('1' + 1); System.out.println("1" + 1 + 1); System.out.println("1" + (1 + 1)); System.out.println('1' + 1 + 1);

System.out.println("1" + 1); => 11 System.out.println('1' + 1); => 50 // (since the Unicode for 1 is 49 System.out.println("1" + 1 + 1); => 111 System.out.println("1" + (1 + 1)); => 12 System.out.println('1' + 1 + 1); => 51

Why does the Math class not need to be imported?

The Math class is in the java.lang package. Any class in the java.lang package is automatically imported. So there is no need to import it explicitly.

whitespace character

The characters ' ', \t, \f, \r, or \n are known as whitespace characters.

What are the differences between a while loop and a do-while loop? Convert the following while loop into a do-while loop. Scanner input = new Scanner(System.in); int sum = 0; System.out.println("Enter an integer " + "(the input ends if it is 0)"); int number = input.nextInt(); while (number != 0) { sum += number; System.out.println("Enter an integer " + "(the input ends if it is 0)"); number = input.nextInt(); }

The difference between a do-while loop and a while loop is the order of evaluating the continuation-condition and executing the loop body. In a while loop, the continuation-condition is checked and then, if true, the loop body is executed. In a do-while loop, the loop body is executed for the first time before the continuation-condition is evaluated. Scanner input = new Scanner(System.in); int sum = 0; int number; do { System.out.println("Enter an integer " + "(the input ends if it is 0)"); number = input.nextInt(); sum += number; } while (number != 0);

What is the keyword break for? What is the keyword continue for? Will the following programs terminate? If so, give the output. (a) int balance = 10; while (true) { if (balance < 9) break; balance = balance - 9; } System.out.println("Balance is " + balance); (b) int balance = 10; while (true) { if (balance < 9) continue; balance = balance - 9; } System.out.println("Balance is " + balance);

The keyword break is used to exit the current loop. The program in (A) will terminate. The output is Balance is 1.The keyword continue causes the rest of the loop body to be skipped for the current iteration.The while loop will not terminate in (B).

What does the following statement do? for ( ; ; ) { // Do something }

The loop keeps doing something indefinitely.

supplementary Unicode

The original Unicode is 16-bit. Those characters that go beyond the original 16-bit limit are called supplementary characters.

What are the format specifiers for outputting a Boolean value, a character, a decimal integer, a floating-point number, and a string?

The specifiers for outputting a boolean value, a character, a decimal integer, a floating-point number, and a string are %b, %c, %d, %f, and %s

What are the three parts of a for loop control? Write a for loop that prints the numbers from 1 to 100.

The three parts in a for loop control are as follows: The first part initializes the control variable. The second part is a Boolean expression that determines whether the loop will repeat. The third part is the adjustment statement, which adjusts the control variable. for (int i = 1; i <= 100; i++) System.out.println(i);

True or false? All the binary operators except = are left associative.

True

True or false? The argument for trigonometric methods is an angle in radians

True

Is x > 0 && x < 10 the same as x > 0 && x < 10? Is x > 0 || x < 10 the same as x > 0 || x < 10? Is (x > 0 || x < 10) && y < 0 the same as (x > 0 || (x < 10 && y < 0))?

Yes Yes Yes

Can you always convert a while loop into a for loop? Convert the following while loop into a for loop. int i = 1; int sum = 0; while (sum < 10000) { sum = sum + i; i++; }

Yes. for (int i=1; sum < 10000; i++) sum = sum + i;

Can you convert a for loop to a while loop? List the advantages of using for loops.

Yes. When using a while loop, programmers often forget to adjust the control variable such as i++. Using for loop can avoid this error.

Suppose that s1, s2, and s3 are three strings, given as follows: String s1 = "Welcome to Java"; String s2 = "Programming is fun"; String s3 = "Welcome to Java"; What are the results of the following expressions? a. s1 == s2 b. s2 == s3 c. s1.equals(s2) d. s1.equals(s3) e. s1.compareTo(s2) f. s2.compareTo(s3) g. s2.compareTo(s2) h. s1.charAt(0) i. s1.indexOf('j') j. s1.indexOf("to") k. s1.lastIndexOf('a') l. s1.lastIndexOf("o", 15) m. s1.length() n. s1.substring(5) o. s1.substring(5, 11) p. s1.startsWith("Wel") q. s1.endsWith("Java") r. s1.toLowerCase() s. s1.toUpperCase() t. s1.concat(s2) u. s1.contains(s2) v. "\t Wel \t".trim()

a. false b. false c. false d. true e. a positive number f. a negative number g. 0 h. W i. -1 j. 8 k. 14 l. 9 m. 15 n. me to Java o. me to p. true q. true r. welcome to java s. WELCOME TO JAVA t. Welcome to JavaProgramming is fun u. false v. Wel

Write a Boolean expression that evaluates to true if age is greater than 13 and less than 18.

age > 13 && age < 18

Analyze the following code. Is count < 100 always true, always false, or sometimes true or sometimes false at Point A, Point B, and Point C? int count = 0; while (count < 100) { // Point A System.out.println("Welcome to Java!"); count++; // Point B } // Point C

count < 100 is always true at Point A.count < 100 always false at Point C.count < 100 is sometimes true or sometimes false at Point B.

Assume that credits is an int variable whose value is 0 or positive. Write an expression whose value is "freshman" or "sophomore" or "junior" or "senior" based on the value of credits. In particular: if the value of credits is less than 30 the expression's value is "freshman"; 30—59 would be a "sophomore", 60—89 would be "junior" and 90 or more would be a "senior".

credits < 30 ? "freshman" : credits < 60 ? "sophomore" : credits < 90 ? "junior" : "senior"

toThePowerOf is a method that accepts two int arguments and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized. Another int variable, cubeVolume, has already been declared.Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3 and that stores this value in cubeVolume. Assume that toThePowerOf is defined in the same class that calls it.

cubeVolume = toThePowerOf ( cubeSide , 3 ) ;

Fall-Through

describes a behavior with a switch statement in which case a matched case statement is executed until a break statement or the end of the switch statement is reached.

Write a statement that converts π / 7 to an angle in degrees and assigns the result to a variable.

double degree = Math.toDegrees(Math.PI / 7);

Write a statement that converts 47 degrees to radians and assigns the result to a variable.

double radians = Math.toRadians(47);

Given an int variable n that has already been declared and initialized to a positive value,use a do...while loop to print a single line consisting of n asterisks. Use no variables other than n.

do{ System.out.print("*"); n--; } while (n > 0);

add is a method that accepts two int arguments and returns their sum. Two int variables, euroSales and asiaSales, have already been declared and initialized. Another int variable, eurasiaSales, has already been declared. Write a statement that calls add to compute the sum of euroSales and asiaSales and that stores this value in eurasiaSales.Assume that add is defined in the same class that calls it.

eurasiaSales = add ( euroSales, asiaSales);

What is the return value from invoking p(27)? public static boolean p(int n) { for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; }

false

Given three String variables that have been declared and given values, firstName, middleName, and lastName, write an expression whose value is the values of each of these variables joined by a single space. So if firstName, middleName, and lastName, had the values "Big", "Bill", and "Broonzy", the expression's value would be "Big Bill Broonzy". Alternatively, if firstName, middleName, and lastName, had the values "Jerry", "Lee", and "Lewis", the expression's value would be "Jerry Lee Lewis

firstName + " " + middleName+ " " + lastName ;

Write a for loop that prints all the even integers from 80 through 20 inclusive, separated by exactly one space

for (int k = 80; k >= 20; k -= 2) System.out.print(k + " ");}

Write a for loop that prints in ascending order all the positive integers less than 200 that are divisible by both 2 and 3, separated by exactly one space.

for (int n = 1; n< 200; n++){ if (n % 2 == 0){ if (n % 3 == 0) System.out.print(n + " ");}}

Write a for loop that prints in ascending order all the positive multiples of 5 that are less than 175, separated by exactly one space.

for (int n = 5; n < 175; n = n + 5){ System.out.print(n + " ");}

Given that a method receives three parameters a, b, c, of type double,write some code, to be included as part of the method, that checks to see if the value of a is 0;if it is, the code prints the message "no solution for a=0" and returns from the method.

if(a == 0) { System.out.print("no solution for a=0"); }

Zeller's congruence is an algorithm developed by Christian Zeller to calculate the day of the week. The formula is : h = ( q + 26(m+1)/10 + k + k/4 + j/4 + 5j) % 7 where - h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday). - q is the day of the month. - m is the month (3: March, 4: April, ..., 12: December). January and February are counted as months 13 and 14 of the previous year. - j is the century (i.e., year/100 ) - k is the year of the century(i.e.,year%100). Note that the division in the formula performs an integer division. Write a program that prompts the user to enter a year, month, and day of the month, and displays the name of the day of the week. Sample Run 1 Enter year: (e.g., 2012): 2015 Enter month: 1-12: 1 Enter the day of the month: 1-31: 25 Day of the week is Sunday Sample Run 2 Enter year: (e.g., 2012): 2012 Enter month: 1-12: 5 Enter the day of the month: 1-31: 12 Day of the week is Saturday Sample Run 3 Enter year: (e.g., 2012): 2002 Enter month: 1-12: 3 Enter the day of the month: 1-31: 26 Day of the week is Tuesday Sample Run 4 Enter year: (e.g., 2012): 2008 Enter month: 1-12: 1 Enter the day of the month: 1-31: 1 Day of the week is Tuesday Sample Run 5 Enter year: (e.g., 2012): 2000 Enter month: 1-12: 2 Enter the day of the month: 1-31: 12 Day of the week is Saturday (Hint: January and February are counted as 13 and 14 in the formula, so you need to convert the user input 1 to 13 and 2 to 14 for the month and change the year to the previous year.) Class Name: Exercise03_21

import java.util.Scanner; public class Exercise_03_21 { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter a year, month, and day of the month. System.out.print("Enter year: (e.g., 2012): "); int year = input.nextInt(); System.out.print("Enter month: 1-12: "); int month = input.nextInt(); System.out.print("Enter the day of the month: 1-31: "); int dayOfMonth = input.nextInt(); // Convert January and February to months 13 and 14 of the previous year if (month == 1 || month == 2) { month = (month == 1) ? 13 : 14; year--; } // Calculate day of the week int dayOfWeek = (dayOfMonth + (26 * (month + 1)) / 10 + (year % 100) + (year % 100) / 4 + (year / 100) / 4 + 5 * (year / 100)) % 7; // Display reslut System.out.print("Day of the week is "); switch(dayOfWeek) { case 0: System.out.println("Saturday"); break; case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); } } }

(Check SSN) Write a program that prompts the user to enter a Social Security Number in the format DDD-DD-DDDD, where D is a digit. Your program should check whether the input is valid. Sample Run 1 Enter a SSN: 232-23-5435 232-23-5435 is a valid social security number Sample Run 2 Enter a SSN: 23-23-5435 23-23-5435 is an invalid social security number Class Name: Exercise04_21

import java.util.Scanner; public class Exercise_04_21 { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter a Social Security number System.out.print("Enter a SSN: "); String ssn = input.nextLine(); // Check whether the input is valid boolean isValid = (ssn.length() == 11) && (Character.isDigit(ssn.charAt(0))) && (Character.isDigit(ssn.charAt(1))) && (Character.isDigit(ssn.charAt(2))) && (ssn.charAt(3) == '-') && (Character.isDigit(ssn.charAt(4))) && (Character.isDigit(ssn.charAt(5))) && (Character.isDigit(ssn.charAt(7))) && (ssn.charAt(6) == '-') && (Character.isDigit(ssn.charAt(8))) && (Character.isDigit(ssn.charAt(9))) && (Character.isDigit(ssn.charAt(10))); // Display result System.out.println(ssn + " is " + ((isValid) ? "a valid " : "an invalid ") + "social security number"); } }

The two roots of a quadratic equation ax^2 + bx + c = 0 can be obtained using the following formula: r1= (- b + sqrt (b^2 - 4ac)) /2a and r2= (- b - sqrt(b^2 - 4ac)) / 2a b^2 - 4ac is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots. Write a program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0, display one root. Otherwise, display "The equation has no real roots". Note that you can use Math.pow(x, 0.5) to compute sqrt(x). Sample Run 1 Enter a, b, c: 1.0 3 1 The equation has two roots -0.381966 and -2.61803 Sample Run 2 Enter a, b, c: 1 2.0 1 The equation has one root -1 Sample Run 3 Enter a, b, c: 1 2 3 The equation has no real roots Class Name: Exercise03_01

import java.util.Scanner; public class Exercise03_01 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a, b, c: "); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double discriminant = b * b - 4 * a * c; if (discriminant < 0) { System.out.println("The equation has no real roots"); } else if (discriminant == 0) { double r1 = -b / (2 * a); System.out.println("The equation has one root " + r1); } else { // (discriminant > 0) double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a); double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a); System.out.println("The equation has two roots " + r1 + " and " + r2); } } }

Vowel or consonant?) Write a program that prompts the user to enter a letter and check whether the letter is a vowel or consonant. For a nonletter input, display invalid input. Sample Run 1 Enter a letter: B B is a consonant Sample Run 2 Enter a letter grade: a a is a vowel Samp[le Run 3 Enter a letter grade: # # is an invalid input Class Name: Exercise04_13

import java.util.Scanner; public class Exercise04_13 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a letter: "); char letter = input.nextLine().charAt(0); if (Character.toUpperCase(letter) == 'A' || Character.toUpperCase(letter) == 'E' || Character.toUpperCase(letter) == 'I' || Character.toUpperCase(letter) == 'O' || Character.toUpperCase(letter) == 'U') System.out.println(letter + " is a vowel"); else if (Character.isLetter(letter)) System.out.println(letter + " is a consonant"); else System.out.println(letter + " is an invalid input");

What is wrong in the following code? import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int value = input.nextInt(); System.out.println("The value is " + value); System.out.print("Enter a line: "); String line = input.nextLine(); System.out.println("The line is " + line); } }

input.nextLine() is used after input.nextInt(). Don't use a line-beased input after a token-based input.

Consider this data sequence: "3 11 5 5 5 2 4 6 6 7 3 -8". Any value that is the same as the immediately preceding value is considered a consecutive duplicate. In this example, there are three such consecutive duplicates: the 2nd and 3rd 5s and the second 6.Note that the last 3 is not a consecutive duplicate because it was preceded by a 7.Write some code that uses a loop to read such a sequence of non-negative integers , terminated by a negative number. When the code finishes executing, the number of consecutive duplicates encountered is printed. In this case, 3 would be printed. Assume the availability of a variable, stdin, that references a Scanner object associated with standard input. That is, stdin = new Scanner(System.in); is given.

int n, prev, consecdups = 0; prev = stdin.nextInt(); n = stdin.nextInt(); while (n >= 0) { if (n == prev) consecdups++; prev = n; n = stdin.nextInt(); } System.out.println(consecdups);

Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive .After the loop terminates, it prints out, on a line by itself and separated by spaces, the sum of all the even integers read,the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by at least one space. Declare any variables that are needed.Assume the availability of a variable, stdin, that references a Scanner object associated with standard input. That is, stdin = new Scanner(System.in); is given. 1

int x; int esum = 0, ecount = 0; int osum = 0, ocount = 0; x = stdin.nextInt(); while (x > 0) { if (x % 2 == 0) { esum += x; ecount++; } else { osum += x; ocount++; } x = stdin.nextInt(); } System.out.println(esum + " " + osum + " " + ecount + " " + ocount);

Write a loop that reads positive integers from standard input, printing out those values that are greater than 100, each followed by a space, and that terminates when it reads an integer that is not positive.Declare any variables that are needed.Assume the availability of a variable, stdin, that references a Scanner object associated with standard input. That is, stdin = new Scanner(System.in); is given.

int x; x = stdin.nextInt(); while (x > 0) { if (x > 100) System.out.print(x + " "); x = stdin.nextInt();

Flowchart

is a diagram that describes an algorithm or a process, showing the steps as boxes of various kinds, and their order by connecting these with arrows.

Boolean Type

is a primitive data type for declaring a variable to store a Boolean value

Boolean Expression

is an expression that evaluates to a Boolean value.

Boolean Value

is either true or false.

Given int variables k and total that have already been declared, use a do...while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total.Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total.Use no variables other than k and total.

k = 1; total = 0; do{ total = total + (k*k);k++; } while (k <= 50);

Given an int variable k that has already been declared, use a while loop to print a single line consisting of 88 asterisks. Use no variables other than k.

k= 1; while (k <= 88) { System.out.print('*'); k++; } System.out.println(); CorrectCorrect!

Given an int variable k that has already been declared, use a do...while loop to print a single line consisting of 53 asterisks. Use no variables other than k.

k=0; do { System.out.print('*'); k++ } while(k<53); System.out.println();

Write an expression that evaluates to true if the value of variable lastName is greater than the string "Dexter".

lastName.compareTo("Dexter")>0

What would be wrong if lines 6-7 in Listing 4.5 is replaced by the following code? String lottery = "" + (int)(Math.random() * 100);

lottery may have only one digit.

Suppose the input is 2 3 4 5 0. What is the output of the following code? import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number, max; number = input.nextInt(); max = number; while (number != 0) { number = input.nextInt(); if (number > max) max = number; } System.out.println("max is " + max); System.out.println("number " + number); } }

max is 5 number 0

max is a method that accepts two int arguments and returns the value of the larger one. Four int variables, population1, population2, population3 and population4 have already been declared and initialized. Write an expression (not a statement!) whose value is the largest of population1, population2, population3 and population4 by calling max. Assume that max is defined in the same class that calls it

max(max(population1, population2), max(population3, population4))

Given the int variables x, y, and z,write a fragment of code that assigns the smallest of x, y, and z to another int variable min.Assume that all the variables have already been declared and that x, y, and z have been assigned values.

min = x; if (y < min) min = y; if (z < min) min = z;

Assume that month is an int variable whose value is 1 or 2 or 3 or 4 or 5 ... or 11 or 12. Write an expression whose value is "jan" or "feb" or "mar" or "apr" or "may" or "jun" or "jul" or "aug" or "sep" or "oct" or "nov" or "dec" based on the value of month. (So, if the value of month were 4 then the value of the expression would be "apr".)

month == 1 ? "jan" : month == 2 ? "feb" : month == 3 ? "mar" : month == 4 ? "apr" : month == 5 ? "may" : month == 6 ? "jun" : month == 7 ? "jul" : month == 8 ? "aug" : month == 9 ? "sep" : month == 10 ? "oct" : month == 11 ? "nov" : "dec"

Given an int variable n that has already been declared, write some code that repeatedly reads a value into n until at last a number between 1 and 10 (inclusive) has been entered.Assume the availability of a variable, stdin, that references a Scanner object associated with standard input. That is, stdin = new Scanner(System.in); is given.

n = -1; while (n < 1 || n > 10) n = stdin.nextInt();

Assume that name is a variable of type String that has been assigned a value. Write an expression whose value is the last character of the value of name. So if the value of name were "Blair", the expression's value would be 'r'.

name.charAt(name.length()-1)

Assume that name is a variable of type String that has been assigned a value. Write an expression whose value is a String containing the last character of the value of name. So if the value of name were "Smith", the expression's value would be "h".

name.substring(name.length()-1)

Rewrite the switch statement in Listing 3.8 using an if-else statement.

nt remainder = year % 12; if (remainder == 0) System.out.println("monkey"); else if (remainder == 1) System.out.println("rooster"); else if (remainder == 2) System.out.println("dog"); else if (remainder == 3) System.out.println("pig"); else if (remainder == 4) System.out.println("rat"); else if (remainder == 5) System.out.println("ox"); else if (remainder == 6) System.out.println("tiger"); else if (remainder == 7) System.out.println("rabbit"); else if (remainder == 8) System.out.println("dragon"); else if (remainder == 9) System.out.println("snake"); else if (remainder == 10) System.out.println("horse"); else System.out.println("sheep");

Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of strings and two int variables, count and longest, write the code necessary to examine all the strings in the input source and determine how long the longest string (or strings are). That value should be assigned to longest. The number of strings that are of that length should be assigned to count.

ount = 0; longest = 0; while (input.hasNext()) { String s = input.next(); if (s.length() > longest) { longest = s.length(); count = 1; } else if (s.length() == longest) count++;

Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, If the user entered month 2 and year 2012, the program should display that February 2012 has 29 days. If the user entered month 3 and year 2015, the program should display that March 2015 has 31 days. Sample Run 1 Enter a month in the year (e.g., 1 for Jan): 2 Enter a year: 2012 February 2012 has 29 days Sample Run 2 Enter a month in the year (e.g., 1 for Jan): 4 Enter a year: 2005 April 2005 has 30 days Sample Run 3 Enter a month in the year (e.g., 1 for Jan): 2 Enter a year: 2006 February 2006 has 28 days Sample Run 4 Enter a month in the year (e.g., 1 for Jan): 2 Enter a year: 2000 February 2000 has 29 days Class Name: Exercise03_11

public class Exercise03_11 { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); // Prompt the user to enter input System.out.print( "Enter a month in the year (e.g., 1 for Jan): "); int month = input.nextInt(); System.out.print("Enter a year: "); int year = input.nextInt(); int numberOfDaysInMonth = 0; switch (month) { case 1: System.out.print("January " + year); numberOfDaysInMonth = 31; break; case 2: System.out.print("February " + year); if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { numberOfDaysInMonth = 29; } else { numberOfDaysInMonth = 28; } break; case 3: System.out.print("March " + year); numberOfDaysInMonth = 31; break; case 4: System.out.print("April " + year); numberOfDaysInMonth = 30; break; case 5: System.out.print("May " + year); numberOfDaysInMonth = 31; break; case 6: System.out.print("June " + year); numberOfDaysInMonth = 30; break; case 7: System.out.print("July " + year); numberOfDaysInMonth = 31; break; case 8: System.out.print("August " + year); numberOfDaysInMonth = 31; break; case 9: System.out.print("September " + year); numberOfDaysInMonth = 30; break; case 10: System.out.print("October " + year); numberOfDaysInMonth = 31; break; case 11: System.out.print("November " + year); numberOfDaysInMonth = 30; break; case 12: System.out.print("December " + year); numberOfDaysInMonth = 31; break; } System.out.print(" has " + numberOfDaysInMonth + " days"); } }

Write the definition of a method add, which receives two int parameters and returns their sum.

public static int add(int a, int b) { return a + b; }

Write the definition of a method twice, which receives an int parameter and returns an int that is twice the value of the parameter.

public static int twice(int x) { return 2 * x; }

Write the definition of a method dashedLine, with one parameter, an int. If the parameter is negative or zero, the method does nothing. Otherwise it prints a complete line terminated by a newline to standard output consisting of dashes (hyphens) with the parameter's value determining the number of dashes. The method returns nothing.

public static void dashedLine(int n) { for (int i = 0; i < n; i++) System.out.print('-'); System.out.println(); }

Write the definition of a method printDottedLine, which has no parameters and doesn't return anything. The method prints to standard output a single line (terminated by a new line) consisting of five periods.

public static void printDottedLine(){ System.out.println(".....");}

Write the definition of a method printGrade, which has a char parameter and returns nothing. The method prints on a line by itself the message string Grade: followed by the char parameter (printed as a character) to standard output. Don't forget to put a new line character at the end of your line.

public static void printGrade(char ch) { System.out.println("Grade: " + ch); }

Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999—2002 as well as all vehicles in its Guzzler line from model years 2004—2007. A boolean variable named recalled has been declared. Given a variable modelYear and a String modelName, write a statement that assigns true to recalled if the values of modelYear and modelName match the recall details and assigns false otherwise.

recalled = modelName.equals("Extravagant") && 1999 <= modelYear && modelYear <= 2002 || modelName.equals("Guzzler") && 2004 <= modelYear && modelYear <= 2007;

Short-Circuit Operator

refers to an operator such as && and ||, which performs a lazy evaluation.

Conditional Operator

refers to the ternary operator with ? and : together that functions like an if-else statement.

Lazy Evaluation

refers to the way on how an expression is evaluated. As soon as the result of the expression is known, the evaluation is terminated.

Write an expression that returns the first character in string s.

s.charAt(0)

Write an expression that evaluates to true if and only if the string variable s equals the string "end".

s.equals("end")

Write an expression that returns the length of a string s.

s.length()

Write an expression that returns a new string with all letters in uppercase from string s.

s.toUpperCase()

Write an expression that evaluates to true if the value of the string variable s1 is greater than the value of string variable s2.

s1.compareTo(s2) > 0

Write the code for invoking a method named sendObject. There is one argument for this method which is of type Customer.Assume that there is a reference to an object of type Customer, in a variable called John_Doe. Use this reference as your argument.Assume that sendObject is defined in the same class that calls it.

sendObject(John_Doe);

Write the code for invoking a method named sendSignal. There are no arguments for this method.Assume that sendSignal is defined in the same class that calls it.

sendSignal();

Suppose the input is 2 3 4 5 0. What is the output of the following code? import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number, sum = 0, count; for (count = 0; count < 5; count++) { number = input.nextInt(); sum += number; } System.out.println("sum is " + sum); System.out.println("count is " + count); } }

sum is 14 count is 5

Write a switch statement that displays Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, if day is 0, 1, 2, 3, 4, 5, 6, accordingly.

switch (day) { case 0: System.out.println("Sunday"); break; case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thurday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; }

HTTP is the protocol that governs communications between web servers and web clients (i.e. browsers). Part of the protocol includes a status code returned by the server to tell the browser the status of its most recent page request. Some of the codes and their meanings are listed below: 200, OK (fulfilled) 403, forbidden 404, not found 500, server error Given an int variable status, write a switch statement that prints out the appropriate label from the above list based on status.

switch (status) { case 200: System.out.println("OK (fulfilled)"); break; case 403: System.out.println("forbidden"); break; case 404: System.out.println("not found"); break; case 500: System.out.println("server error"); break; }

In the Happy Valley School System, children are classified by age as follows: less than 2, ineligible 2, toddler 3—5, early childhood 6—7, young reader 8—10, elementary 11 and 12, middle 13, impossible 14—16, high school 17—18, scholar greater than 18, ineligible Given an int variable age, write a switch statement that prints out, on a line by itself, the appropriate label from the above list based on age.

switch(age) { case 0: case 1: System.out.println("ineligible"); break; case 2: System.out.println("toddler"); break; case 3: case 4: case 5: System.out.println("early childhood"); break; case 6: case 7: System.out.println("young reader"); break; case 8: case 9: case 10: System.out.println("elementary"); break; case 11: case 12: System.out.println("middle"); break; case 13: System.out.println("impossible"); break; case 14: case 15: case 16: System.out.println("high school"); break; case 17: case 18: System.out.println("scholar"); break; default: System.out.println("ineligible"); break; }

Given the variables temperature and humidity, write an expression that evaluates to true if and only if the temperature is greater than 90 and the humidity is less than 10.

temperature > 90 && humidity < 10

Assume that the String variable named text has already been declared. Assign to it the empty string.

text = "";

Rewrite the following if statements using the conditional operator. if (ages >= 16) ticketPrice = 20; else ticketPrice = 10;

ticketPrice = (ages >= 16) ? 20 : 10;

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a for loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Use no variables other than n, k, and total.

total = 0; for (k = n; k >= 0; k--) total = total + (k*k*k);

Given int variables k and total that have already been declared, use a for loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total.Use no variables other than k and total.

total = 0; for (k=1; k <= 50; k++) total = total + (k*k);

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a do...while loop to compute the sum of the cubes of the first n whole numbers, and store this value in total.Use no variables other than n, k, and total.

total = 0; k = n; do { total += k * k * k; k--; } while(k > 0);

Given int variables k and total that have already been declared, use a while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total.Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total. Use no variables other than k and total.

total=0; k=50; while (k>0) { total+=k*k; k--;

What is the return value from invoking p(7)? public static boolean p(int n) { for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; }

true

Write a Boolean expression that evaluates to true if weight is greater than 50 pounds and height is greater than 60 inches.

weight > 50 && height > 60.

Write a Boolean expression that evaluates to true if either weight is greater than 50 pounds or height is greater than 60 inches, but not both.

weight > 50 ^ height > 60.

Write a Boolean expression that evaluates to true if weight is greater than 50 pounds or height is greater than 60 inches.

weight > 50 || height > 60.

Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of lines, write the code necessary to read in every line and print them all out on a single line, separated by a space.Hint: Use input.nextLine() to read a line and use input.hasNextLine() to test if the input has a next line available to read.

while (input.hasNextLine()) { System.out.print(input.nextLine()); if (input.hasNextLine()) System.out.print(" "); } System.out.println();

Given an int variable n that has already been declared and initialized to a positive value, use a while loop to print a single line consisting of n asterisks. Use no variables other than n.

while (n > 0) { System.out.print('*'); n--; } System.out.println();

Convert the following for loop statement to a while loop and to a do-while loop: long sum = 0; for (int i = 0; i <= 1000; i++) sum = sum + i;

while loop: long sum = 0; int i=0; while (i <= 1000) { sum += i++; } do-while loop: do-while loop: long sum = 0; int i = 0; do { sum += i++; } while (i <= 1000);

Assume that x and y are int type. Which of the following are legal Java expressions? x > y > 0 x = y && y x /= y x or y x and y (x != 0) || (x = 0)

x > y > 0 is incorrect x = y && y is incorrect x /= y is correct x or y is incorrect x and y is incorrect (x != 0) || (x = 0) is incorrect on x = 0. It should be x == 0.

Given that the variables x and y have already been declared and assigned values, write an expression that evaluates to true if x is non-negative and y is negative.

x >= 0 && y < 0

Given that the variables x and y have already been declared and assigned values, write an expression that evaluates to true if x is positive (including zero) or y is negative.

x >= 0 || y < 0

What is the output of the following code? Explain the reason. int x = 80000000; while (x > 0) x++; System.out.println("x is " + x);

x is -2147483648The reason: When a variable is assigned a value that is too large (in size) to be stored, it causes overflow.2147483647 + 1 is actually -2147483648

What is x after the following if-else statement is executed? Use a switch statement to rewrite it and draw the flowchart for the new switch statement. int x = 1, a = 3; if (a == 1) x += 5; else if (a == 2) x += 10; else if (a == 3) x += 16; else if (a == 4) x += 34;

x is 17 switch (a) { case 1: x += 5; break; case 2: x += 10; break; case 3: x += 16; break; case 4: x += 34; } picture on your ipad

floor(x)

x is rounded down to its nearest integer. This integer is returned as a double value.


Conjuntos de estudio relacionados

Civics - Chapter 5 Section 3 Notes

View Set

MGT 340 Final (cumulative, exams 1 - 4 in order)

View Set

ATI Nursing Fundamentals - Chapter 16-25: Nursing Throughout the Lifespan

View Set