Chapter 2: Data and Expressions

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What value will z have if we execute the following assignment statement? float z = 5 / 10; a) z will equal 0.0 b) z will equal 0.5 c) z will equal 5.0 d) z will equal 0.05 e) none of the above, a run-time error arises because z is a float and 5 / 10 is an int

A) 5 and 10 are both int values, so 5 / 10 is an integer division. The result is 0. Even though z is a float and can store the real answer, 0.5, it only gets 0 because of the integer division. In order to get 0.5, we would have to first cast 5 or 10 as a float.

What is output with the statement System.out.println(x+y); if x and y are int values where x=10 and y=5? a) 15 b) 105 c) 10 5 d) x+y e) An error since neither x nor y is a String

A) Java first computes x+y and then casts it as a String to be output. x + y = 10 + 5 = 15, so the statement outputs 15.

public class Questions1_4 { public static void main(String[ ] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } A reasonable comment for this program might be: a) // a program that demonstrates the differences between print, println and how + works b) // a program that outputs a message about Texas c) // a program that demonstrates nothing at all d) // a program that outputs the message "Here There Everywhere But not in Texas" e) // a program that contains three output statements

A) Remember that comments should not state the obvious (ruling out d and e) but instead should explain what the program is doing or why. This program demonstrates print and println and +.

If you want to output a double so that at least 1 digit appears to the left side of the decimal point and exactly 1 digit appears to the right side of the decimal point, which pattern would you give a DecimalFormat variable when you instantiate it? a) "0.0" b) "0.#" c) "0.0#" d) "0.##" e) "#.#"

A) The pattern "0.0" says to output all of the digits to the left of the decimal point or a 0 if there are none (you want at least 1 digit to the left, including a 0 if there are no digits) and exactly one digit to the right of the decimal point, even if the digit is 0. The patterns "0.#" and "#.#" would not output any digits to the right side of the decimal point if the value had no decimal portion (e.g., 39.0). The patterns in c and d can output up to 2 values to the right of the decimal point.

The word println is a(n): a) method b) reserved word c) variable d) class e) String

A) The word println is passed as a message to the System.out object, and so println is a method.

Assume that x, y, and z are all ints equal to 50, 20, and 6 respectively. What is the result of x / y / z? a) 0 b) 12 c) 16 d) A syntax error as this is syntactically invalid e) A run-time error because this is a division by 0

A) This division is performed left to right, so first 50 / 20 is performed. Since 50 and 20 are ints, this results in 2. Next, 2 / 6 is performed which is 0. Notice that if the division were performed right to left, the evaluation would instead be 50 / (20 / 6) = 50 / 3 = 16.

If you want to draw a red circle inside of a green square in an applet where the paint method is passed a Graphics object called page, which of the following sets of commands might you use? a) page.setColor(Color.green); page.fillRect(50, 50, 100, 100); page.setColor(Color.red); page.fillOval(60, 60, 80, 80); b) page.setColor(Color.red); page.fillOval(60, 60, 80, 80); page.setColor(Color.green); page.fillRect(50, 50, 100, 100); c) page.setColor(Color.green); page.fillRect(60, 60, 80, 80); page.setColor(Color.red); page.fillOval(50, 50, 100, 100); d) page.setColor(Color.red); page.fillOval(50, 50, 100, 100); page.setColor(Color.green); page.fillRect(60, 60, 80, 80); e) any of the above would accomplish this.

A) You need to draw the background (larger) image first. This is the square in green. The square will be larger, so it starts at 50, 50 and is of size 100 x 100. Next, draw the circle in red inside the square, so it will start at 60, 60 and be smaller in size at 80 x 80. Answer b will accomplish the same drawings but in opposite order so that the circle is drawn over, thus blocking it as if it weren't there.

If a, b, and c are int variables with a = 5, b = 7, c = 12, then the statement int z = (a * b - c) / a; will result in z equal to a) 0 b) 4 c) 5 d) -5 e) 23

B) (a x b - c) / a = (5 x 7 - 12) / 5 = (35 - 12) / 5 = 23 / 5, and since 23 and 5 are int values, the division is performed as an int division, or 23 / 5 = 4.

If the String major = "Computer Science", what is returned by major.charAt(1)? a) 'C' b) 'o' c) 'm' d) "C" e) "Computer"

B) Neither d nor e would be correct because charAt returns a char (single character) whereas these answers are Strings. So, the question is, which character is returned? In Java, the first character of a String is numbered 0. So charAt(1) returns the second character of the String, or 'o'.

If x is an int and y is a float, all of the following are legal except which assignment statement? a) y = x; b) x = y; c) y = (float) x; d) x = (int) y; e) all of the above are legal

B) Since x is an int, it cannot except a float unless the float is cast as an int. There is no explicit cast in the assignment statement in b. In a, a cast is not necessary because a float (y) can accept an int value (x), and in c and d, explicit casts are present making them legal.

What is output with the statement System.out.println(""+x+y); if x and y are int values where x=10 and y=5? a) 15 b) 105 c) 10 5 d) x+y e) An error since neither x nor y is a String

B) The "" casts the rest of the expression as a String, and so the two + signs are used as String concatenation. Therefore x + y becomes x concatenated with y, or 105.

public class Questions1_4 { public static void main(String[ ] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } The final println command will output: a) "But not in Texas" b) "But notin Texas" c) "But not" on one line and "in Texas" on the next line d) "But not+in Texas" e) "But not + in Texas"

B) The "+" performs String concatenation, so that "But not" and "in Texas" are concatenated together. Notice that there is no blank space after "not" or before "in" so that when they are concatenated, they are placed together without a blank space.

import java.util.Scanner; public class Questions33_34 { public static void main(String[ ] args) { int x, y, z; double average; Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer value"); x = scan.nextInt( ); System.out.println("Enter another integer value"); y = scan.nextInt( ); System.out.println("Enter a third integer value"); z = scan.nextInt( ); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } } What is output if x = 0, y = 1 and z = 1? a) 0 b) 0.0 c) 0.6666666666666666 d) 0.6666666666666667 e) 0.67

B) The division is performed as an int division since x, y, z, and 3 are all ints. Therefore, average gets the value 0.0. It is output as 0.0 instead of 0 because average is a double, which outputs at least one decimal digit unless specified otherwise using the DecimalFormat class.

Consider the double value likelihood = 0.013885. What would be output if DecimalFormat dformatter = DecimalFormat("0.00##"); and you execute System.out.println(df.format(likelihood)); ? a) 0.013885 b) 0.0139 c) 0.014 d) .0139 e) .014

B) The format "0.00##" means that at least 1 digit should appear to the left of the decimal point, even if it is 0, that at least two digits should appear to the right of the decimal point even if they are zeros, and if there are two additional digits to the right, they should also be printed, rounding the value off as needed. So, this gives 0.0139 since the number, 0.013885 will be rounded up to 0.0139.

The Random class has a method nextFloat( ) which returns a random float value between a) -1 and +1 b) 0 and 1 c) 0 and 99 d) 1 and 100 e) -2,147,483,648 and +2,147,483,647

B) The method nextFloat( ) returns a float value between 0 and 1 so that it may be used as a probability.

Suppose that String name = "Frank Zappa". What will the instruction name.toUpperCase( ).replace('A', 'I'); return? a) "FRANK ZAPPA " b) "FRINK ZIPPI" c) "Frink Zippi" d) "Frank Zappa" e) "FrInk ZIppI"

B) The toUpperCase method returns the String as all upper case characters, or "FRANK ZAPPA". The replace method will replace each instance of 'A' with 'I'.

public class Questions1_4 { public static void main(String[ ] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } How many lines of output are provided by this program? a) 1 b) 2 c) 3 d) 4 e) 5

B) There will be one line of output for the first two statements combined because the print statement does not return the cursor to start a new line. And since the second statement is a println, it returns the cursor and the last println outputs its message on a separate line.

A Java variable is the name of a: a) numeric data value stored in memory b) data value stored in memory that can not change during the program's execution c) data value stored in memory that can not change its type during the program's execution d) data value stored in memory that can change both its value and its type during the program's execution e) data value or a class stored in memory that can change both its value and its type during the program's execution

C) A variable can change its value as long as it is within the same type, but the variable cannot change type. A constant is similar to a variable but it cannot change its value. Variables can be numeric but are not restricted to being numeric, they can also be boolean, char, or an object of any class.

import java.util.Scanner; public class Questions33_34 { public static void main(String[ ] args) { int x, y, z; double average; Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer value"); x = scan.nextInt( ); System.out.println("Enter another integer value"); y = scan.nextInt( ); System.out.println("Enter a third integer value"); z = scan.nextInt( ); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } } Question33_34 computes a) The correct average of x, y and z as a double b) The correct average of x, y and z as an int c) The average of x, y, and z as a double, but the result may not be accurate d) the sum of x, y and z e) the remainder of the sum of x, y and z divided by 3

C) Because the division is an int division, even though the result is stored in a double, the resulting double may not be accurate. For instance, if x, y and z are 1, 2, and 4, the double average should be 2.33333 but average will instead be 2.00000.

Since you cannot take the square root of a negative number, you might use which of the following instructions to find the square root of the variable x? a) Math.sqrt(x*x); b) Math.sqrt((int) x); c) Math.sqrt(Math.abs(x)); d) Math.abs(Math.sqrt(x)); e) Math.sqrt(-x);

C) Math.abs returns the absolute value of x. If x is negative, Math.sqrt(x) causes a runtime error, but Math.sqrt(Math.abs(x)) does not since x is first converted to its positive equivalent before the square root is performed. Answer a returns x (square root of x2 is x). In answer b, casting x to an int will not resolve the problem if x is negative. In answer d, the two Math functions are performed in opposite order and so if x is negative, it still generates a run-time error. Answer e only will work if x is not positive and so if x is positive, it now generates a run-time error.

Given the following assignment statement, which of the following answers is true regarding the order that the operators will be applied based on operator precedence? a = (b + c) * d / e - f; a) *, /, +, - b) *, +, /, - c) +, *, /, - d) +, /, *, - e) +, -, *, /

C) Order of precedence is any operator in ( ) first, followed by * and / in a left-to-right manner, followed by + and - in a left-to-right manner. So, + is first since it is in ( ), followed by * followed by / since * is to the left of /, followed finally by -.

Java is a strongly typed language. What is meant by "strongly typed"? a) Every variable must have an associated type before you can use it b) Variables can be used without declaring their type c) Every variable has a single type associated with it throughout its existence in the program, and the variable can only store values of that type d) Variables are allowed to change type during their existence in the program as long as the value it currently stores is of the type it is currently declared to be e) Variables are allowed to change types during their existence in the program but only if the change is to a narrower type

C) Strong typing is a property of a programming language whereby the variable's type does not change during the variable's existence, and any value stored in that variable is of that type. The reason that strong typing is important is it guarantees that a program that was successfully compiled will not have run-time errors associated with the misuse of types for the variables declared.

You specify the shape of an oval in a Java applet by defining the oval's a) arc locations b) center and radius c) bounding box d) foci e) none of the above, it is not possible to draw an oval in a Java applet

C) The bounding box is the box that defines the height and width of the oval along with the (x, y) coordinate that are the highest and left-most point of the oval.

public void paint(Graphics page) { page.setColor(Color.blue); page.fillRect(50, 50, 100, 100); page.setColor(Color.white); page.drawLine(50, 50, 150, 150); page.drawLine(50, 150, 150, 50); page.setColor(Color.black); page.drawString("A nice box", 50, 170); } The figure drawn in this applet is a) a blue square b) a blue square with two white lines drawn horizontally through it c) a blue square with two white lines drawn diagonally through it d) a blue square with two white lines drawn vertically through it e) a white square with two blue lines drawn vertically through it

C) The color set before fillRect is blue, so the square is blue. The two lines are white and they are drawn from the upper left corner (50, 50) to the lower right corner (150, 150) and from the lower left corner (50, 150) to the upper right corner (150, 50).

Consider having three String variables a, b, and c. The statement c = a + b; also can be achieved by saying a) c = a.length( ) + b.length( ); b) c = (int) a + (int) b; c) c = a.concat(b); d) c = b.concat(a); e) c = a.plus(b);

C) The statement c = a + b uses the concatenation operator + (not to be confused with numeric addition). The same result can be achieved by passing a the concat message with b as the parameter. Answer d will set c to be b + a rather than a + b.

Which library package would you import to use NumberFormat and DecimalFormat? a) java.beans b) java.io c) java.lang d) java.text e) java.util

D) Both of these classes are used for "text processing", that is, to handle values like Strings. Such classes are found in java.text. You might think these would be in java.io, but this library has classes related to input and sending output to locations other than the monitor.

A cast is required in which of the following situations? a) using charAt to take an element of a String and store it in a char b) storing an int in a float c) storing a float in a double d) storing a float in an int e) all of the above require casts

D) For a, charAt returns a char, so there is no problem. In b and c, the situations are widening operations taking a narrower type and storing the value in a wider type. Only in d is there a situation where a wider type is being stored in a narrower type, so a cast is required.

Which of the following would return the last character of the String x? a) x.charAt(0); b) x.charAt(last); c) x.charAt(length(x)); d) x.charAt(x.length( )-1); e) x.charAt(x.length( ));

D) Since last is not defined, b is syntactically invalid. The 0th character is the first in the String, so a is true only if the String has a single character. The answer in c is syntactically invalid as length can only be called by passing the message to x. Finally, d and e are syntactically valid, but since length returns the size of the String, and since the first character starts at the 0th position, the last character is at x.length()-1, so e would result in a run-time error.

public void paint(Graphics page) { page.setColor(Color.blue); page.fillRect(50, 50, 100, 100); page.setColor(Color.white); page.drawLine(50, 50, 150, 150); page.drawLine(50, 150, 150, 50); page.setColor(Color.black); page.drawString("A nice box", 50, 170); } The String "A nice box" is drawn a) above the box b) to the left of the box c) to the right of the box d) below the box e) inside the box

D) The String is drawn at coordinates (50, 170) so the x-coordinate lines up with the left-side of the box, but the y-coordinate, 170, is below the bottom edge of the box which is at y=150.

In order to create a constant, you would use which of the following Java reserved words? a) private b) static c) int d) final e) class

D) The reserved word final indicates that this is the final value that will be stored in this variable, thus making it unchangeable, or constant. While constants can be of type int, constants can be of any other type as well. It is the final reserved word that makes the value unchangeable.

What will be the result of the following assignment statement? Assume b = 5 and c = 10. int a = b * (-c + 2) / 2; a) 30 b) -30 c) 20 d) -20 e) -6

D) The unary minus is applied first giving -c + 2 = -8. Next, the * is performed giving 5 * -8 = -40, and finally the / is performed giving -40 / 2 = -20.

If you want to output the text "hi there", including the quote marks, which of the following could do that? a) System.out.println("hi there"); b) System.out.println(""hi there""); c) System.out.println("\"hi there"); d) System.out.println("\"hi there\""); e) none, it is not possible to output a quote mark because it is used to mark the beginning and ending of the String to be output.

D) \" is an escape sequence used to place a quote mark in a String, so it is used here to output the quote marks with the rest of the String.

Of the following types, which one cannot store a numeric value? a) int b) byte c) float d) char e) all of these can store numeric values

D) int and byte are used to store whole numbers (integers) and float is used to store a real or floating point value (value with a decimal point). A char stores a single character including letters, punctuation marks and digits. However, storing the numeric digit '5' is not the same as storing the number 5.

Assume that x is a double that stores 0.362491. To output this value as 36%, you could use the NumberFormat class with NumberFormat nf = NumberFormat.getPercentInstance( ); Which of the following statements then would output x as 36%? a) System.out.println(x); b) System.out.println(nf); c) System.out.println(nf.x); d) System.out.println(nf.format(x)); e) System.out.println(format(x));

D) nf is an object and so must be passed a message to use it. The method to format a float or double is called format and the value to be formatted is the parameter passed to format. Therefore, the proper way to do this is nf.format(x). The answer in a merely outputs 0.362491 while the answers to b, c, and e are syntactically invalid.

What value will z have if we execute the following assignment statement? int z = 50 / 10.00; a) 5 b) 5.0 c) 50 d) 10 e) none of the above, a run-time error arises because z is an int and 50 / 10.00 is not

E) Because 10.00 is not an int, the division produces a double precision value which cannot be stored in the int z. For this to work, the result of the division must be cast as an int before being stored in z, or the value 10.00 would have to first be cast as an int before the division takes place.

Which of the following is true regarding the mod operator, %? a) It can only be performed on int values and its result is a double b) It can only be performed on int values and its result is an int c) It can only be performed on float or double values and its result is an int d) It can only be performed on float or double values and its result is a double e) It can be performed on any numeric values, and the result always is numeric

E) Mod, or modulo, returns the remainder that results from a division. The remainder is always is numeric. Although usually integer values are used, the % operator may be used on all kinds of numeric data.

If you want to store into the String name the value "George Bush", you would do which statement? a) String name = "George Bush"; b) String name = new String("George Bush"); c) String name = "George" + " " + "Bush"; d) String name = new String("George" + " " + "Bush"); e) Any of the above would work

E) There are two ways to store a character string into a String variable, by constructing a new String using "new String(string value);" or by using an assignment statement, so either a or b will work. In c and d, we have variations where the String concatenation operator + is used. So all four approaches will work.

Which library package would you import to use the class Random? a) java.beans b) java.io c) java.lang d) java.text e) java.util

E) This is a java numeric utility, and so is found in the java.util package.

Using getCurrencyInstance( ) formats a variable, automatically inserting a) decimal point for cents b) dollar sign c) percent sign d) all three e) a and b but not c

E) getCurrencyInstance will format a double or float variable so that it has 2 digits to the right of the decimal point and a dollar sign preceding the value. getPercentInstance is used to to format a double or float to be output with a percent sign.

True or False: A variable of type boolean will store either a 0 or a 1.

False. A boolean variable can store only one of two values, but these values are the reserved words true and false. In C, C++, and C# booleans are implemented as int variables that store only a 0 or a 1, but in Java, the authors of the language opted to use the boolean literals true and false as this is considered to be semantically more understandable (and is much safer).

True or False: The values of (double) 5 / 2 and (double) (5 / 2) are identical.

False. In the first expression, the (double) cast applies to the int 5, changing it to the double value, 5.0. Then 5.0 / 2 is calculated, yielding the double value, 2.5. In the second expression the int division is performed first, yielding the value 2. 2 is then changed to a double, yielding the double value, 2.0.

True or False: The Java graphics coordinate system is similar to the coordinate system one finds in mathematics in every respect.

False. The Java coordinate system is similar to the one from mathematics, but the following important differences are present: (1) The Java coordinate system only uses non-negative integers as coordinates, not real values, and no negative coordinates are allowed; (2) The (0, 0) location is a the top-left of the coordinate system, with positive y running downwards instead of at the bottom-left, with positive y running upwards.

True or False: Java is able to represent 255 x 255 x 255 = 16,581,375 distinct colors.

False. The red, green, and blue color components range between 0 and 255, yielding 256 distinct values for each. Therefore, 256 x 256 x 256 = 16,777,216 distinct colors can be represented.

True or False: In order to generate a random number, you must use Math.random( ).

False. There is also a Random class available in java.util. This class can generate random int, float, and double values. This is a better mechanism for generating random numbers because you can instantiate several different random number generators.

True or False: If x is the String "Hi There", then x.toUpperCase().toLowerCase(); will return the original version of x.

False. x.toUpperCase() returns x as all capital letters, while x.toLowerCase() will return x as all lower case letters. So, this code will first convert x to all upper case letters and then convert the new version to all lower case characters.

Assume that a = "1", b = "2", y = 3 and z = 4. How do the following two statements differ? System.out.println(a + b + y + z); System.out.println(y + z + a + b);

In the first statement, since a and b are Strings, a + b + c + d is treated as String concatenation and the statement outputs 1234. In the second statement, y + z is treated as int addition, which is then cast as a String to be concatenated with y + z, giving 712 instead of 3412 as you might expect.

How do the statements "import java.util.*;" and "import java.util.Random;" differ from each other?

In the former, all of the classes defined in the java.util library are imported whereas in the latter, only the Random class is imported from the java.util library. The former approach is easier but more time consuming and wasteful of memory, so the latter approach is more appropriate if you only want to use a single class from a given library.

Write a set of instructions to prompt the user for an int value and input it using the Scanner class into the variable x and prompt the user for a float value and input it using the Scanner class into the variable y.

Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer"); int x = scan.nextInt( ); System.out.println("Enter a float"); float y = scan.nextFloat( );

Using the various String methods, manipulate a String called current to be current's last character followed by the remainder of its characters in order, placing the result in a String called rearranged.

String rearranged = current.charAt(current.length( ) - 1) + current.substring(0, current.length( ) - 1); The last character, which is found at charAt(current.length( ) - 1) is the first item in rearranged, followed by the substring of current starting at 0 (the first character) and going to current.length( ) - 2 (the second to last character).

Write an output statement which will output the following characters exactly as shown: / ' \" / ' \

System.out.println("/ \ ' \ \ \" / \ ' \ \ ");

Consider the following statement: System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); This statement will output ___ lines of text a) 1 b) 2 c) 3 d) 4 e) 5

The correct answer is dependent on whether or not you are using an IDE. If you run the code in an IDE you will get 3 lines of code (C). While if you run using the command prompt, you will get only 2 (B). B) The \t escape sequence inserts a tab, but leaves the cursor on the same line. The \n escape sequence causes a new line to be produced so that "4 dinner" is output on the next line. The escape sequence \r causes the carriage to return (that is, the cursor to be moved back to the left margin) but because it does not start a new line, "2night" is output over "4 dinn" resulting in a second line that looks like "2nighter".

What is wrong with the following assignment statement? Assume x and y are both String objects. String z = x.equals(y);

The equals method returns a boolean value, not a String. The values true and false are not the same as the values "true" and "false".

Explain, in words, what the following statement computes: int z = (int) Math.ceil(Math.sqrt(x) / Math.sqrt(y));

The integer value which bounds sqrt(x) / sqrt(y) where bounds means it is equal to the result of the division or the next int larger than the result of the division if the result has a remainder.

What are the syntax errors from the following program? public class Enigma { public static void main(String[ ] args) { System.out.println("Input a String"); String x = scan.nextString( ); int size = x.length; char last = x.charAt(size); System.out.println("The last character in your string ", x, " is ", last); } }

There are 3 syntax errors. First, the Scanner class has not been import so that the scan.nextString( ) will yield a syntax error. Second, the statement x.length requires parentheses as length is a method of the class String, so this is a message passed to x. Finally, the System.out.println statement is not valid because of the use of "," instead of "+" to concatenate the various parts of the String. Note that in spite of these syntax errors, there is a run-time error. This error would arise because size will store the length of the String, but the last character will be at location size - 1 instead of size. Thus, the statement char last = x.charAt(size); will result in a run-time error because size is beyond the bounds of the String x.

How many ways are there to test to see if two String variables, a and b, are equal to each other if we ignore their case (for instance, "aBCd" would be considered equal to "ABcd").

There are at least 10 ways that this can be done: a.toLowerCase( ).equals(b.toLowerCase( )); b.toLowerCase( ).equals(a.toLowerCase( )); a.toUpperCase( ).equals(b.toUpperCase( )); b.toUpperCase( ).equals(a.toUpperCase( )); a.equalsIgnoreCase(b); b.equalsIgnoreCase(a); a.equalsIgnoreCase(b.toLowerCase( )); a.equalsIgnoreCase(b.toUpperCase( )); b.equalsIgnoreCase(a.toLowerCase( )); b.equalsIgnoreCase(a.toUpperCase( ));

True or False: Many Java drawing shapes are specified using a bounding rectangle.

True. Although a few shapes (like a line) are specified using start-point-end-point combinations, most Java shapes use a bounding rectangle specified by a starting point, width, and height.

True or False: There are three ways that data conversion may occur - by assignment, by promotion, by casting.

True. Assignment conversion occurs when a value on the right side of the assignment operator is converted prior to being stored in the variable on the left. Promotion occurs within an expression when values of differing widths are combined. Casting is a programmer's explicit way to control the data conversion process.

True or False: In Java, 'a' and 'A' are considered to be different values.

True. Characters (char) values are stored using ASCII, and 'a' and 'A' have different ASCII values as well as different Unicode values.

True or False: If x is a string, then x = new String("OH"); and x = "OH"; will accomplish the same thing.

True. In Java, to instantiate (assign a value to) an object, you must use new and the class's constructor. However, since Strings are so common in Java, they can be instantiated in a way similar to assigning primitive types their values. So, both of the above assignment statements will accomplish the same task.

True or False: If String a = "ABCD" and String b = "abcd" then a.equals(b); returns false but a.equalsIgnoreCase(b); returns true.

True. Since "ABCD" is not the same as "abcd", the equals method returns false, but by ignoring case in equalsIgnoreCase, the two are considered to be the same.

True or False: Unlike the String class where you must pass a message to an object (instance) of the class, as in x.length( ), in order to use either the Scanner or Math classes, you pass messages directly to the class name, as in Math.abs( ) or scan.nextInt( ).

True. The Math and Scanner classes use methods known as static methods (or class methods) which are invoked by passing a message directly to the class name itself rather than to an object of the class.

True or False: If String name = "George W. Bush"; then the instruction name.length(); will return 14.

True. There are 14 characters between the quote marks including two blanks and a period.

True or False: You cannot cast a String to be a char and you cannot cast a String which stores a number to be an int, float or double.

True. There is no mechanism available to cast a String to one of the primitive types, but there are methods available to perform a similar action and return a character at a given location (charAt) or to return the int, float or double value equivalent to the number stored in the String.

True or False: A double is wider than a float and a float is wider than an int.

True. Wider types are larger in size or can store a greater range of values. The double is 64 bits whereas the float is 32 bits and the float, because of the way it is stored, can store a significantly larger range of values than the int.

Provide an example of how you might use a boolean, a float, a char, a String, and an int.

boolean: to store whether a person is of voting age or not float: to store someone's GPA char: to store someone's middle initial String: to store someone's social security number int: to store someone's age

Given four int values, x1, x2, y1, y2, write the code to compute the distance between the two points (x1, y1) and (x2, y2), storing the result in the double distance.

double distance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) ;

Write an assignment statement to compute the gas mileage of a car where the int values miles_traveled and gallons_needed have already been input. The variable gas_mileage needs to be declared and should be a double.

double gas_mileage = (double) miles_traveled / gallons_needed; The reason that the value miles_traveled is cast as a double is to ensure that the division is performed as a double and not an int.

Write a program which will input an int value x, and compute and output the values of 2^x and x^10 as int values.

import java.util.Scanner; public class Compute { public static void main(String[ ] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer value"); int x = scan.nextInt( ); int twoToTheX = (int) Math.pow(2, x); int xToThe10th = (int) Math.pow(x, 10); System.out.println("The results are " + twoToTheX + " and " + xToThe10th); } }

Write a program that will input some number of cents (less than 100) and output the number of quarters, dimes, nickels and pennies needed to add up to that amount.

import java.util.Scanner; public class Change { public static void main(String[ ] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter the amount of change"); int amount = scan.nextInt( ); System.out.println("The change for " + amount + " cents is: "); int quarters = amount / 25; System.out.println(" " + quarters + " quarters"); amount = amount - quarters * 25; int dimes = amount / 10; System.out.println(" " + dimes + " dimes"); amount = amount - dimes * 10; int nickels = amount / 5; System.out.println(" " + nickels + " nickels"); amount = amount - nickels * 5; int pennies = amount; System.out.println(" " + pennies + " pennies"); } }

Provide three examples of code using assignment statements where one assignment statement would result in a syntax error, one would result in a logical error, and one would result in a run-time error.

int x = 5.0 / 2.0; // syntax error caused by right side providing a double and the left side wants an int double x = (intValue1 + intValue2) / 2; // logical error caused by not casting the division as a double int x = 5 / (y - y); // run-time error caused by division by 0 when y - y is evaluated

An applet is 200x200. Write the Strings "North", "South", "East", and "West" at the four edges of the applet where they should appear as if on a map. Use the color black for the text.

public void paint(Graphics page) { page.setColor(Color.black); page.drawString("North", 90, 10); page.drawString("South", 90, 190); page.drawString("East", 5, 90); page.drawString("West", 170, 90); }

Given two points in an applet represented by the four int variables x1, y1, x2 and y2, write a paint method to draw a line between the two points and write the location of the two points next to the two points.

public void paint(Graphics page) { page.setColor(Color.blue); page.drawLine(x1, y1, x2, y2); page.drawString("" + x1 + ", " + y1, x1, y1); page.drawString("" + x2 + ", " + y2, x2, y2); }

Write the paint method for an applet so that it contains 4 concentric circles (each circle is inside the previous circle), where the largest circle is bounded by a 400x400 box and the smallest is bounded by a 100x100 box. Each circle is centered on an applet that is 400x400. Make each circle a different color of your choice.

public void paint(Graphics page) { page.setColor(Color.white); page.fillOval(0, 0, 400, 400); page.setColor(Color.yellow); page.fillOval(50, 50, 300, 300); page.setColor(Color.orange); page.fillOval(100, 100, 200, 200); page.setColor(Color.red); page.fillOval(150, 150, 100, 100); }

An employer has decided to award a weekly pay raise to all employees by taking the square root of the difference between his weight and the employee's weight. For instance, an employee who weighs 16 pounds less than the employer will get a $4 per week raise. The raise should be in whole dollars (an int). Assume that employerWeight and employeeWeight are both int variables that have been input, write an assignment statement to compute the int value for raise.

raise = (int) Math.sqrt(Math.abs(employerWeight - employeeWeight)); The absolute value of the difference must be taken in case the employee weighs more than the employer, which would then result in an attempt to take the square root of a negative number if Math.abs were not used. After computing the absolute value of the difference, the square root is taken and the result (a double) is cast as an int to be stored in raise.


संबंधित स्टडी सेट्स

Section 1 - Relational Databases

View Set

HUMAN BEHAVIOR 2 FINAL TEST DEC 15 2018

View Set