soru ve cevaplar

Ace your homework & exams now with Quizwiz!

What does the following code output? 1: public class Salmon { 2: int count; 3: public void Salmon() { 4: count = 4; 5: } 6: public static void main(String[] args) { 7: Salmon s = new Salmon(); 8: System.out.println(s.count); 9: } } A. 0 B. 4 C. Compilation fails on line 3. D. Compilation fails on line 4. E. Compilation fails on line 7. F. Compilation fails on line 8.

A. While the code on line 3 does compile, it is not a constructor because it has a return type. It is a method that happens to have the same name as the class. When the code runs, the default constructor is called and count has the default value (0) for an int.

Which of the following are true? (Choose all that apply) A. An array has a fixed size. B. An ArrayList has a fixed size. C. An array allows multiple dimensions. D. An array is ordered. E. An ArrayList is ordered. F. An array is immutable. G. An ArrayList is immutable.

A, C, D, E. An array is not able to change size and can have multiple dimensions. Both an array and ArrayList are ordered and have indexes. Neither is immutable. The elements can change in value.

Which are the results of the following code? (Choose all that apply) String numbers = "012345678"; System.out.println(numbers.substring(1, 3)); System.out.println(numbers.substring(7, 7)); System.out.println(numbers.substring(7)); A. 12 B. 123 C. 7 D. 78 E. A blank line. F. An exception is thrown. G. The code does not compile.

A, D, E. substring() has two forms. The first takes the index to start with and the index to stop immediately before. The second takes just the index to start with and goes to the end of the String. Remember that indexes are zero based. The first call starts at index 1 and ends with index 2 since it needs to stop before index 3. The second call starts at index 7 and ends in the same place, resulting in an empty String. This prints out a blank line. The final call starts at index 7 and goes to the end of the String.

What is the output of the following code snippet? 3: int x1 = 50, x2 = 75; 4: boolean b = x1 >= x2; 5: if(b = true) System.out.println("Success"); 6: else System.out.println("Failure"); A. Success B. Failure C. The code will not compile because of line 4. D. The code will not compile because of line 5.

A. The code compiles successfully, so options C and D are incorrect. The value of b after line 4 is false. However, the if-then statement on line 5 contains an assignment, not a comparison. The variable b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success, so the answer is option A.

What is the result of the following code? public class Lion { public void roar(String roar1, StringBuilder roar2) { roar1.concat("!!!"); roar2.append("!!!"); } public static void main(String[] args) { String roar1 = "roar"; StringBuilder roar2 = new StringBuilder("roar"); new Lion().roar(roar1, roar2); System.out.println(roar1 + " " + roar2); } } A. roar roar B. roar roar!!! C. roar!!! roar D. roar!!! roar!!! E. An exception is thrown. F. The code does not compile.

B. A String is immutable. Calling concat() returns a new String but does not change the original. A StringBuilder is mutable. Calling append() adds characters to the existing character sequence along with returning a reference to the same object.

What is the output of the following code? LocalDateTime d = LocalDateTime.of(2015, 5, 10, 11, 22, 33); Period p = Period.ofDays(1).ofYears(2); d = d.minus(p); DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle .SHORT); System.out.println(f.format(d)); A. 5/9/13 11:22 AM B. 5/10/13 11:22 AM C. 5/9/14 D. 5/10/14 E. The code does not compile. F. A runtime exception is thrown.

B. Period does not allow chaining. Only the last Period method called counts, so only the two years are subtracted.

What is the output of the following code? LocalDate date = LocalDate.of(2018, Month.APRIL, 30); date.plusDays(2); date.plusYears(3); System.out.println(date.getYear() + " " + date.getMonth() + " " + date.getDayOfMonth()); A. 2018 APRIL 2 B. 2018 APRIL 30 C. 2018 MAY 2 D. 2021 APRIL 2 E. 2021 APRIL 30 F. 2021 MAY 2 G. A runtime exception is thrown.

B. The date starts out as April 30, 2018. Since dates are immutable and the plus methods have their return values ignored, the result is unchanged. Therefore, option B is correct.

What is the output of the following code snippet? 3: int x = 0; 4: String s = null; 5: if(x == s) System.out.println("Success"); 6: else System.out.println("Failure"); A. Success B. Failure C. The code will not compile because of line 4. D. The code will not compile because of line 5.

D. The variable x is an int and s is a reference to a String object. The two data types are incomparable because neither variable can be converted to the other variable's type. The compiler error occurs on line 5 when the comparison is attempted, so the answer is option D.

What is the output of the following code snippet? 3: do { 4: int y = 1; 5: System.out.print(y++ + " "); 6: } while(y <= 10); 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 6 7 8 9 10 11 D. The code will not compile because of line 6. E. The code contains an infinite loop and does not terminate.

D. The variable y is declared within the body of the do-while statement, so it is out of scope on line 6. Line 6 generates a compiler error, so option D is the correct answer.

Which of the following Java operators can be used with boolean variables? (Choose all that apply) A. == B. + C. -- D. ! E. % F. <=

A, D. Option A is the equality operator and can be used on numeric primitives, boolean values, and object references. Options B and C are both arithmetic operators and cannot be applied to a boolean value. Option D is the logical complement operator and is used exclusively with boolean values. Option E is the modulus operator, which can only be used with numeric primitives. Finally, option F is a relational operator that compares the values of two numbers.

Which of the following are true? (Choose all that apply) A. An instance variable of type boolean defaults to false. B. An instance variable of type boolean defaults to true. C. An instance variable of type boolean defaults to null. D. An instance variable of type int defaults to 0. E. An instance variable of type int defaults to 0.0. F. An instance variable of type int defaults to null. G. None of the above.

A, D. Options A and D are correct because boolean primitives default to false and int primitives default to 0.

Given the following classes, which of the following snippets can be inserted in place of INSERT IMPORTS HERE and have the code compile? (Choose all that apply) package aquarium; public class Water { boolean salty = false; } package aquarium.jellies; public class Water { boolean salty = true; } package employee; INSERT IMPORTS HERE public class WaterFiller { Water water; } A. import aquarium.*; B. import aquarium.Water;import aquarium.jellies.*; C. import aquarium.* ; import aquarium.jellies.Water; D. import aquarium.*; import aquarium.jellies.*; E. import aquarium.Water;import aquarium.jellies.Water; F. None of these imports can make the code compile.

A, B, C. Option A is correct because it imports all the classes in the aquarium package including aquarium.Water. Options B and C are correct because they import Water by classname. Since importing by classname takes precedence over wildcards, these compile. Option D is incorrect because Java doesn't know which of the two wildcard Water classes to use. Option E is incorrect because you cannot specify the same classname in two imports.

Which of the following are true statements about the following code? (Choose all that apply) 4: List<Integer> ages = new ArrayList<>(); 5: ages.add(Integer.parseInt("5")); 6: ages.add(Integer.valueOf("6")); 7: ages.add(7); 8: ages.add(null); 9: for (int age : ages) System.out.print(age); A. The code compiles. B. The code throws a runtime exception. C. Exactly one of the add statements uses autoboxing. D. Exactly two of the add statements use autoboxing. E. Exactly three of the add statements use autoboxing.

A, B, D. Lines 5 and 7 use autoboxing to convert an int to an Integer. Line 6 does not because valueOf() returns an Integer. Line 8 does not because null is not an int. The code does not compile. However, when the for loop tries to unbox null into an int, it fails and throws a NullPointerException.

What data type (or types) will allow the following code snippet to compile? (Choose all that apply) byte x = 5; byte y = 10; _____ z = x + y; A. int B. long C. boolean D. double E. short F. byte

A, B, D. The value x + y is automatically promoted to int, so int and data types that can be promoted automatically from int will work. Options A, B, D are such data types. Option C will not work because boolean is not a numeric data type. Options E and F will not work without an explicit cast to a smaller data type.

Which of the following are valid Java identifiers? (Choose all that apply) A. A$B B. _helloWorld C. true D. java.lang E. Public F. 1980_s

A, B, E. Option A is valid because you can use the dollar sign in identifiers. Option B is valid because you can use an underscore in identifiers. Option C is not a valid identifier because true is a Java reserved word. Option D is not valid because the dot (.) is not allowed in identifiers. Option E is valid because Java is case sensitive, so Public is not a reserved word and therefore a valid identifier. Option F is not valid because the first character is not a letter, $, or _.

Given the following class, which of the following is true? (Choose all that apply) 1: public class Snake { 2: 3: public void shed(boolean time) { 4: 5: if (time) { 6: 7: } 8: System.out.println(result); 9: 10: } 11: } A. If String result = "done"; is inserted on line 2, the code will compile. B. If String result = "done"; is inserted on line 4, the code will compile. C. If String result = "done"; is inserted on line 6, the code will compile. D. If String result = "done"; is inserted on line 9, the code will compile. E. None of the above changes will make the code compile.

A, B. Adding the variable at line 2 makes result an instance variable. Since instance variables are in scope for the entire life of the object, option A is correct. Option B is correct because adding the variable at line 4 makes result a local variable with a scope of the whole method. Adding the variable at line 6 makes result a local variable with a scope of lines 6-7. Since it is out of scope on line 8, the println does not compile and option C is incorrect. Adding the variable at line 9 makes result a local variable with a scope of lines 9 and 10. Since line 8 is before the declaration, it does not compile and option D is incorrect. Finally, option E is incorrect because the code can be made to compile.

Which of the following legally fill in the blank so you can run the main() method from the command line? (Choose all that apply) public static void main( ) A. String[] _names B. String[] 123 C. String abc[] D. String _Names[] E. String... $n F. String names G. None of the above.

A, C, D, E. Option A is correct because it is the traditional main() method signature and variables may begin with underscores. Options C and D are correct because the array operator may appear after the variable name. Option E is correct because varargs are allowed in place of an array. Option B is incorrect because variables are not allowed to begin with a digit. Option F is incorrect because the argument must be an array or varargs. Option F is a perfectly good method. However, it is not one that can be run from the command line because it has the wrong parameter type.

Which of the following are output by this code? (Choose all that apply) 3: String s = "Hello"; 4: String t = new String(s); 5: if ("Hello".equals(s)) System.out.println("one"); 6: if (t == s) System.out.println("two"); 7: if (t.equals(s)) System.out.println("three"); 8: if ("Hello" == s) System.out.println("four"); 9: if ("Hello" == t) System.out.println("five"); A. one B. two C. three D. four E. five F. The code does not compile.

A, C, D. The code compiles fine. Line 3 points to the String in the string pool. Line 4 calls the String constructor explicitly and is therefore a different object than s. Lines 5 and 7 check for object equality, which is true, and so print one and three. Line 6 uses object reference equality, which is not true since we have different objects. Line 7 also compares references but is true since both references point to the object from the string pool. Finally, line 8 compares one object from the string pool with one that was explicitly constructed and returns false.

Which of the following can replace line 4 to print "avaJ"? (Choose all that apply) 3: StringBuilder puzzle = new StringBuilder("Java"); 4: // INSERT CODE HERE 5: System.out.println(puzzle); A. puzzle.reverse(); B. puzzle.append("vaJ$").substring(0, 4); C. puzzle.append("vaJ$").delete(0, 3).deleteCharAt(puzzle.length() - 1); D. puzzle.append("vaJ$").delete(0, 3).deleteCharAt(puzzle.length()); E. None of the above.

A, C. The reverse() method is the easiest way of reversing the characters in a String- Builder; therefore, option A is correct. Option B is a nice distraction—it does in fact return "avaJ". However, substring() returns a String, which is not stored anywhere. Option C uses method chaining. First it creates the value "JavavaJ$". Then it removes the first three characters, resulting in "avaJ$". Finally, it removes the last character, resulting in "avaJ". Option D throws an exception because you cannot delete the character after the last index. Remember that deleteCharAt() uses indexes that are zero based and length() counts starting with 1.

Which of the following are true? (Choose all that apply) public class Bunny { public static void main(String[] args) { Bunny bun = new Bunny(); } } A. Bunny is a class. B. bun is a class. C. main is a class. D. Bunny is a reference to an object. E. bun is a reference to an object. F. main is a reference to an object. G. None of the above.

A, E. Bunny is a class, which can be seen from the declaration: public class Bunny. bun is a reference to an object. main() is a method.

Which of the following lines of code compile? (Choose all that apply) A. int i1 = 1_234; B. double d1 = 1_234_.0; C. double d2 = 1_234._0; D. double d3 = 1_234.0_; E. double d4 = 1_234.0; F. None of the above.

A, E. Underscores are allowed as long as they are directly between two other digits. This means options A and E are correct. Options B and C are incorrect because the underscore is adjacent to the decimal point. Option D is incorrect because the underscore is the last character.

What is the result of the following code? (Choose all that apply) StringBuilder numbers = new StringBuilder("0123456789"); numbers.delete(2, 8); numbers.append("-").insert(2, "+"); System.out.println(numbers); A. 01+89- B. 012+9- C. 012+-9 D. 0123456789 E. An exception is thrown. F. The code does not compile.

A. First, we delete the characters at index 2 until the character one before index 8. At this point, 0189 is in numbers. The following line uses method chaining. It appends a dash to the end of the characters sequence, resulting in 0189-, and then inserts a plus sign at index 2, resulting in 01+89-.

What is the result of the following? 4: List<Integer> list = Arrays.asList(10, 4, -1, 5); 5: Collections.sort(list); 6: Integer array[] = list.toArray(new Integer[4]); 7: System.out.println(array[0]); A. -1 B. 10 C. Compiler error on line 4. D. Compiler error on line 5. E. Compiler error on line 6. F. An exception is thrown.

A. Line 4 creates a fixed size array of size 4. Line 5 sorts it. Line 6 converts it back to an array. The brackets aren't in the traditional place, but they are still legal. Line 7 prints the first element, which is now -1.

What is the output of the following code? 1: public class ArithmeticSample { 2: public static void main(String[] args) { 3: int x = 5 * 4 % 3; 4: System.out.println(x); 5: }} A. 2 B. 3 C. 5 D. 6 E. The code will not compile because of line 3.

A. The * and % have the same operator precedence, so the expression is evaluated from left-to-right. The result of 5 * 4 is 20, and 20 % 3 is 2 (20 divided by 3 is 18, the remainder is 2). The output is 2 and option A is the correct answer.

What is the output of the following code snippet? 3: int count = 0; 4: ROW_LOOP: for(int row = 1; row <=3; row++) 5: for(int col = 1; col <=2 ; col++) { 6: if(row * col % 2 == 0) continue ROW_LOOP; 7: count++; 8: } 9: System.out.println(count); A. 1 B. 2 C. 3 D. 4 E. 6 F. The code will not compile because of line 6.

A. The expression on line 5 is true when row * col is an even number. On the first iteration, row = 1 and col = 1, so the expression on line 6 is false, the continue is skipped, and count is incremented to 1. On the second iteration, row = 1 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with count still at 1. On the third iteration, row = 2 and col = 1, so the expression on line 6 is true and the continue ends the outer loop with count still at 1. On the fourth iteration, row = 3 and col = 1, so the expression on line 6 is false, the continue is skipped, and count is incremented to 2. Finally, on the fifth and final iteration, row = 3 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with count still at 2. The result of 2 is displayed, so the answer is option B.

In this chapter, you learned that Strings are immutable sequences of characters. The new operator is optional. The concatenation operator (+) creates a new String with the content of the fi rst String followed by the content of the second String. If either operand involved in the + expression is a String, concatenation is used; otherwise, addition is used. String literals are stored in the string pool. The String class has many methods. You need to know charAt(), concat(), endsWith(), equals(), equalsIgnoreCase(), indexOf(), length(), replace(), startsWith(), substring(), toLowerCase(), toUpperCase(), and trim(). StringBuilders are mutable sequences of characters. Most of the methods return a reference to the current object to allow method chaining. The StringBuilder class has many methods. You need to know append(), charAt(), delete(), deleteCharAt(), indexOf(), insert(), length(), reverse(), substring(), and toString(). StringBuffer is the same as StringBuilder except that it is thread safe. Calling == on String objects will check whether they point to the same object in the pool. Calling == on StringBuilder references will check whether they are pointing to the same StringBuilder object. Calling equals() on String objects will check whether the sequence of characters is the same. Calling equals() on StringBuilder objects will check whether they are pointing to the same object rather than looking at the values inside.

An array is a fi xed-size area of memory on the heap that has space for primitives or pointers to objects. You specify the size when creating it—for example, int[] a = new int[6];. Indexes begin with 0 and elements are referred to using a[0]. The Arrays.sort() method sorts an array. Arrays.binarySearch() searches a sorted array and returns the index of a match. If no match is found, it negates the position where the element would need to be inserted and subtracts 1. Methods that are passed varargs (...) can be used as if a normal array was passed in. In a multidimensional array, the second-level arrays and beyond can be different sizes. An ArrayList can change size over its life. It can be stored in an ArrayList or List reference. Generics can specify the type that goes in the ArrayList. You need to know the methods add(), clear(), contains(), equals(), isEmpty(), remove(), set(), and size(). Although an ArrayList is not allowed to contain primitives, Java will autobox parameters passed in to the proper wrapper type. Collections.sort() sorts an ArrayList. A LocalDate contains just a date, a LocalTime contains just a time, and a LocalDateTime contains both a date and time. All three have private constructors and are created using LocalDate.now() or LocalDate.of() (or the equivalents for that class). Dates and times can be manipulated using plusXXX or minusXXX methods. The Period class represents a number of days, months, or years to add or subtract from a LocalDate or LocalDateTime. DateTimeFormatter is used to output dates and times in the desired format. The date and time classes are all immutable, which means the return value must be used.

What change would allow the following code snippet to compile? (Choose all that apply) 3: long x = 10; 4: int y = 2 * x; A. No change; it compiles as is. B. Cast x on line 4 to int. C. Change the data type of x on line 3 to short. D. Cast 2 * x on line 4 to int. E. Change the data type of y on line 4 to short. F. Change the data type of y on line 4 to long.

B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x is automatically promoted to long and cannot be automatically stored in y, which is in an int value. Options B, C, and D solve this problem by reducing the long value to int. Option E does not solve the problem and actually makes it worse by attempting to place the value in a smaller data type. Option F solves the problem by increasing the data type of the assignment so that long is allowed.

Given the following class, which of the following lines of code can replace INSERT CODE HERE to make the code compile? (Choose all that apply) public class Price { public void admission() { INSERT CODE HERE System.out.println(amount); } } A. int amount = 9L; B. int amount = 0b101; C. int amount = 0xE; D. double amount = 0xE; E. double amount = 1_2_.0_0; F. int amount = 1_2_; G. None of the above.

B, C, D. 0b is the prefix for a binary value and is correct. 0x is the prefix for a hexadecimal value. This value can be assigned to many primitive types, including int and double, making options C and D correct. Option A is incorrect because 9L is a long value. long amount = 9L would be allowed. Option E is incorrect because the underscore is immediately before the decimal. Option F is incorrect because the underscore is the very last character.

Which are true statements? (Choose all that apply) A. An immutable object can be modified. B. An immutable object cannot be modified. C. An immutable object can be garbage collected. D. An immutable object cannot be garbage collected. E. String is immutable. F. StringBuffer is immutable. G. StringBuilder is immutable.

B, C, E. Immutable means the state of an object cannot change once it is created. Immutable objects can be garbage collected just like mutable objects. String is immutable. StringBuilder can be mutated with methods like append(). Although StringBuffer isn't on the exam, you should know about it anyway in case older questions haven't been removed.

Which of the following are true? (Choose all that apply) A. Two arrays with the same content are equal. B. Two ArrayLists with the same content are equal. C. If you call remove(0) using an empty ArrayList object, it will compile successfully. D. If you call remove(0) using an empty ArrayList object, it will run successfully. E. None of the above.

B, C. An array does not override equals() and so uses object equality. ArrayList does override equals() and defines it as the same elements in the same order. The compiler does not know when an index is out of bounds and thus can't give you a compiler error. The code will throw an exception at runtime, though.

Which of the following are true? (Choose all that apply) 4: short numPets = 5; 5: int numGrains = 5.6; 6: String name = "Scruffy"; 7: numPets.length(); 8: numGrains.length(); 9: name.length(); A. Line 4 generates a compiler error. B. Line 5 generates a compiler error. C. Line 6 generates a compiler error. D. Line 7 generates a compiler error. E. Line 8 generates a compiler error. F. Line 9 generates a compiler error. G. The code compiles as is.

B, D, E. Option A (line 4) compiles because short is an integral type. Option B (line 5) generates a compiler error because int is an integral type, but 5.6 is a floating-point type. Option C (line 6) compiles because it is assigned a String. Options D and E (lines 7 and 8) do not compile because short and int are primitives. Primitives do not allow methods to be called on them. Option F (line 9) compiles because length() is defined on String.

Which are the results of the following code? (Choose all that apply) String letters = "abcdef"; System.out.println(letters.length()); System.out.println(letters.charAt(3)); System.out.println(letters.charAt(6)); A. 5 B. 6 C. c D. d E. An exception is thrown. F. The code does not compile.

B, D, E. length() is simply a count of the number of characters in a String. In this case, there are six characters. charAt() returns the character at that index. Remember that indexes are zero based, which means that index 3 corresponds to d and index 6 corresponds to 1 past the end of the array. A StringIndexOutOfBoundsException is thrown for the last line.

What is the output of the following code snippet? 3: java.util.List<Integer> list = new java.util.ArrayList<Integer>(); 4: list.add(10); 5: list.add(14); 6: for(int x : list) { 7: System.out.print(x + ", "); 8: break; 9: } A. 10, 14, B. 10, 14 C. 10, D. The code will not compile because of line 7. E. The code will not compile because of line 8. F. The code contains an infinite loop and does not terminate.

C. This code does not contain any compilation errors or an infinite loop, so options D, E, and F are incorrect. The break statement on line 8 causes the loop to execute once and finish, so option C is the correct answer.

Suppose we have a class named Rabbit. Which of the following statements are true? (Choose all that apply) 1: public class Rabbit { 2: public static void main(String[] args) { 3: Rabbit one = new Rabbit(); 4: Rabbit two = new Rabbit(); 5: Rabbit three = one; 6: one = null; 7: Rabbit four = one; 8: three = null; 9: two = null; 10: two = new Rabbit(); 11: System.gc(); 12: } } A. The Rabbit object from line 3 is first eligible for garbage collection immediately following line 6. B. The Rabbit object from line 3 is first eligible for garbage collection immediately following line 8. C. The Rabbit object from line 3 is first eligible for garbage collection immediately following line 12. D. The Rabbit object from line 4 is first eligible for garbage collection immediately following line 9. E. The Rabbit object from line 4 is first eligible for garbage collection immediately following line 11. F. The Rabbit object from line 4 is first eligible for garbage collection immediately following line 12.

B, D. The Rabbit object from line 3 has two references to it: one and three. The references are nulled out on lines 6 and 8, respectively. Option B is correct because this makes the object eligible for garbage collection after line 8. Line 7 sets the reference four to the now null one, which means it has no effect on garbage collection. The Rabbit object from line 4 only has a single reference to it: two. Option D is correct because this single reference becomes null on line 9. The Rabbit object declared on line 10 becomes eligible for garbage collection at the end of the method on line 12. Calling System.gc() has no effect on eligibility for garbage collection.

Which of the following are true statements? (Choose all that apply) A. Java allows operator overloading. B. Java code compiled on Windows can run on Linux. C. Java has pointers to specific locations in memory. D. Java is a procedural language. E. Java is an object-oriented language. F. Java is a functional programming language.

B, E. C++ has operator overloading and pointers. Java made a point of not having either. Java does have references to objects, but these are pointing to an object that can move around in memory. Option B is correct because Java is platform independent. Option E is correct because Java is object oriented. While it does support some parts of functional programming, these occur within a class.

What is true about the following code? (Choose all that apply) public class Bear { protected void finalize() { System.out.println("Roar!"); } public static void main(String[] args) { Bear bear = new Bear(); bear = null; System.gc(); } } A. finalize() is guaranteed to be called. B. finalize() might or might not be called C. finalize() is guaranteed not to be called. D. Garbage collection is guaranteed to run. E. Garbage collection might or might not run. F. Garbage collection is guaranteed not to run. G. The code does not compile.

B, E. Calling System.gc() suggests that Java might wish to run the garbage collector. Java is free to ignore the request, making option E correct. finalize() runs if an object attempts to be garbage collected, making option B correct.

Given the following class, which of the following calls print out Blue Jay? (Choose all that apply) public class BirdDisplay { public static void main(String[] name) { System.out.println(name[1]); } } A. java BirdDisplay Sparrow Blue Jay B. java BirdDisplay Sparrow "Blue Jay" C. java BirdDisplay Blue Jay Sparrow D. java BirdDisplay "Blue Jay" Sparrow E. java BirdDisplay.class Sparrow "Blue Jay" F. java BirdDisplay.class "Blue Jay" Sparrow G. Does not compile.

B. Option B is correct because arrays start counting from zero and strings with spaces must be in quotes. Option A is incorrect because it outputs Blue. C is incorrect because it outputs Jay. Option D is incorrect because it outputs Sparrow. Options E and F are incorrect because they output Error: Could not find or load main class Bird- Display.class.

What is the result of the following code snippet? 3: final char a = 'A', d = 'D'; 4: char grade = 'B'; 5: switch(grade) { 6: case a: 7: case 'B': System.out.print("great"); 8: case 'C': System.out.print("good"); break; 9: case d: 10: case 'F': System.out.print("not good"); 11: } A. great B. greatgood C. The code will not compile because of line 3. D. The code will not compile because of line 6. E. The code will not compile because of lines 6 and 9.

B. The code compiles and runs without issue, so options C, D, and E are not correct. The value of grade is 'B' and there is a matching case statement that will cause "great" to be printed. There is no break statement after the case, though, so the next case statement will be reached, and "good" will be printed. There is a break after this case statement, though, so the switch statement will end. The correct answer is thus option B.

What is the result of the following? List<String> one = new ArrayList<String>(); one.add("abc"); List<String> two = new ArrayList<>(); two.add("abc"); if (one == two) System.out.println("A"); else if (one.equals(two)) System.out.println("B"); else System.out.println("C"); A. A B. B C. C D. An exception is thrown. E. The code does not compile.

B. The first if statement is false because the variables do not point to the same object. The second if statement is true because ArrayList implements equality to mean the same elements in the same order.

What is the output of the following code snippet? 3: boolean x = true, z = true; 4: int y = 20; 5: x = (y != 10) ^ (z=false); 6: System.out.println(x+", "+y+", "+z); A. true, 10, true B. true, 20, false C. false, 20, true D. false, 20, false E. false, 20, true F. The code will not compile because of line 5.

B. This example is tricky because of the second assignment operator embedded in line 5. The expression (z=false) assigns the value false to z and returns false for the entire expression. Since y does not equal 10, the left-hand side returns true; therefore, the exclusive or (^) of the entire expression assigned to x is true. The output reflects these assignments, with no change to y, so option B is the only correct answer. The code compiles and runs without issue, so option F is not correct.

What is the result of the following code? 7: StringBuilder sb = new StringBuilder(); 8: sb.append("aaa").insert(1, "bb").insert(4, "ccc"); 9: System.out.println(sb); A. abbaaccc B. abbaccca C. bbaaaccc D. bbaaccca E. An exception is thrown. F. The code does not compile.

B. This example uses method chaining. After the call to append(), sb contains "aaa". That result is passed to the first insert() call, which inserts at index 1. At this point sb contains abbbaa. That result is passed to the final insert(), which inserts at index 4, resulting in abbaccca.

Which represent the order in which the following statements can be assembled into a program that will compile successfully? (Choose all that apply) A: class Rabbit {} B: import java.util.*; C: package animals; A. A, B, C B. B, C, A C. C, B, A D. B, A E. C, A F. A, C G. A, B

C, D, E. package and import are both optional. If both are present, the order must be package, then import, then class. Option A is incorrect because class is before package and import. Option B is incorrect because import is before package. Option F is incorrect because class is before package. Option G is incorrect because class is before import.

Which of the following are true? (Choose all that apply) A. javac compiles a .class file into a .java file. B. javac compiles a .java file into a .bytecode file. C. javac compiles a .java file into a .class file. D. Java takes the name of the class as a parameter. E. Java takes the name of the .bytecode file as a parameter. F. Java takes the name of the .class file as a parameter.

C, D. Java puts source code in .java files and bytecode in .class files. It does not use a .bytecode file. When running a Java program, you pass just the name of the class without the .class extension.

Which of the following are true? (Choose all that apply) A. An instance variable of type double defaults to null. B. An instance variable of type int defaults to null. C. An instance variable of type String defaults to null. D. An instance variable of type double defaults to 0.0. E. An instance variable of type int defaults to 0.0. F. An instance variable of type String defaults to 0.0. G. None of the above.

C, D. Option C is correct because all non-primitive values default to null. Option D is correct because float and double primitives default to 0.0. Options B and E are incorrect because int primitives default to 0.

Given the following classes, which of the following can independently replace INSERT IMPORTS HERE to make the code compile? (Choose all that apply) package aquarium; public class Tank { } package aquarium.jellies; public class Jelly { } package visitor; INSERT IMPORTS HERE public class AquariumVisitor { public void admire(Jelly jelly) { } } A. import aquarium.*; B. import aquarium.*.Jelly; C. import aquarium.jellies.Jelly; D. import aquarium.jellies.*; E. import aquarium.jellies.Jelly.*; F. None of these can make the code compile.

C, D. Option C is correct because it imports Jelly by classname. Option D is correct because it imports all the classes in the jellies package, which includes Jelly. Option A is incorrect because it only imports classes in the aquarium package—Tank in this case—and not those in lower-level packages. Option B is incorrect because you cannot use wildcards anyplace other than the end of an import statement. Option E is incorrect because you cannot import parts of a class with a regular import statement. Option F is incorrect because options C and D do make the code compile.

Which of these array declarations is not legal? (Choose all that apply) A. int[][] scores = new int[5][]; B. Object[][][] cubbies = new Object[3][0][5]; C. String beans[] = new beans[6]; D. java.util.Date[] dates[] = new java.util.Date[2][]; E. int[][] types = new int[]; F. int[][] java = new int[][];

C, E, F. Option C uses the variable name as if it were a type, which is clearly illegal. Options E and F don't specify any size. Although it is legal to leave out the size for later dimensions of a multidimensional array, the first one is required. Option A declares a legal 2D array. Option B declares a legal 3D array. Option D declares a legal 2D array. Remember that it is normal to see on the exam types you might not have learned. You aren't expected to know anything about them.

What is the result of the following statements? 3: ArrayList<Integer> values = new ArrayList<>(); 4: values.add(4); 5: values.add(5); 6: values.set(1, 6); 7: values.remove(0); 8: for (Integer v : values) System.out.print(v); A. 4 B. 5 C. 6 D. 46 E. 45 F. An exception is thrown. G. The code does not compile.

C. After line 4, values has one element (4). After line 5, values has two elements (4, 5). After line 6, values has two elements (4, 6) because set() does a replace. After line 7, values has only one element (6).

Which of these compile when replacing line 8? (Choose all that apply) 7: char[]c = new char[2]; 8: // INSERT CODE HERE A. int length = c.capacity; B. int length = c.capacity(); C. int length = c.length; D. int length = c.length(); E. int length = c.size; F. int length = c.size(); G. None of the above.

C. Arrays define a property called length. It is not a method, so parentheses are not allowed.

What is the result of the following? 6: String [] names = {"Tom", "Dick", "Harry"}; 7: List<String> list = names.asList(); 8: list.set(0, "Sue"); 9: System.out.println(names[0]); A. Sue B. Tom C. Compiler error on line 7. D. Compiler error on line 8. E. An exception is thrown.

C. Converting from an array to an ArrayList uses Arrays.asList(names). There is no asList() method on an array instance. If this code were corrected to compile, the answer would be option A.

What is the output of the following code snippet? 3: int c = 7; 4: int result = 4; 5: result += ++c; 6: System.out.println(result); A. 8 B. 11 C. 12 D. 15 E. 16 F. The code will not compile because of line 5.

C. The code compiles successfully, so option F is incorrect. On line 5, the pre-increment operator is used, so c is incremented to 4 and the new value is returned to the expression. The value of result is computed by adding 4 to the original value of 8, resulting in a new value of 12, which is output on line 6. Therefore, option C is the correct answer.

What is the result of the following code? 3: String s = "purr"; 4: s.toUpperCase(); 5: s.trim(); 6: s.substring(1, 3); 7: s += " two"; 8: System.out.println(s.length()); A. 2 B. 4 C. 8 D. 10 E. An exception is thrown. F. The code does not compile.

C. This question is trying to see if you know that String objects are immutable. Line 4 returns "PURR" but the result is ignored and not stored in s. Line 5 returns "purr" since there is no whitespace present but the result is again ignored. Line 6 returns "ur" because it starts with index 1 and ends before index 3 using zero-based indexes. The result is ignored again. Finally, on line 6 something happens. We concatenate four new characters to s and now have a String of length 8.

Which of the following can be inserted into the blank to create a date of June 21, 2014? (Choose all that apply) import java.time.*; public class StartOfSummer { public static void main(String[] args) { LocalDate date = ____________________________ } } A. new LocalDate(2014, 5, 21); B. new LocalDate(2014, 6, 21); C. LocalDate.of(2014, 5, 21); D. LocalDate.of(2014, 6, 21); E. LocalDate.of(2014, Calendar.JUNE, 21); F. LocalDate.of(2014, Month.JUNE, 21);

D, F. Options A and B are incorrect because LocalDate does not have a public constructor. Option C is incorrect because months start counting with 1 rather than 0. Option E is incorrect because it uses the old pre-Java 8 way of counting months, again beginning with 0. Options D and F are both correct ways of specifying the desired date.

What is the output of the following code? LocalDate date = LocalDate.parse("2018-04-30", DateTimeFormatter.ISO_LOCAL_ DATE); date.plusDays(2); date.plusHours(3); System.out.println(date.getYear() + " " + date.getMonth() + " " + date.getDayOfMonth()); A. 2018 APRIL 2 B. 2018 APRIL 30 C. 2018 MAY 2 D. The code does not compile. E. A runtime exception is thrown.

D. A LocalDate does not have a time element. Therefore, it has no method to add hours and the code does not compile.

What is the result of the following? List<String> hex = Arrays.asList("30", "8", "3A", "FF"); Collections.sort(hex); int x = Collections.binarySearch(hex, "8"); int y = Collections.binarySearch(hex, "3A"); int z = Collections.binarySearch(hex, "4F"); System.out.println(x + " " + y + " " + z); A 0 1 -2 B. 0 1 -3 C. 2 1 -2 D. 2 1 -3 E. None of the above. F. The code doesn't compile.

D. After sorting, hex contains [30, 3A, 8, FF]. Remember that numbers sort before letters and strings sort alphabetically. This makes 30 come before 8. A binary search correctly finds 8 at index 2 and 3A at index 1. It cannot find 4F but notices it should be at index 2. The rule when an item isn't found is to negate that index and subtract 1. Therefore, we get -2-1, which is -3.

What is the output of the following code? LocalDateTime d = LocalDateTime.of(2015, 5, 10, 11, 22, 33); Period p = Period.of(1, 2, 3); d = d.minus(p); DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); System.out.println(d.format(f)); A. 3/7/14 11:22 AM B. 5/10/15 11:22 AM C. 3/7/14 D. 5/10/15 E. 11:22 AM F. The code does not compile. G. A runtime exception is thrown.

E. Even though d has both date and time, the formatter only outputs time.

What is the output of the following code? 1: public class TernaryTester { 2: public static void main(String[] args) { 3: int x = 5; 4: System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7); 5: }} A. 5 B. 4 C. 10 D. 8 E. 7 F. The code will not compile because of line 4.

D. As you learned in the section "Ternary Operator," although parentheses are not required, they do greatly increase code readability, such as the following equivalent statement: System.out.println((x > 2) ? ((x < 4) ? 10 : 8) : 7) We apply the outside ternary operator fi rst, as it is possible the inner ternary expression may never be evaluated. Since (x>2) is true, this reduces the problem to: System.out.println((x < 4) ? 10 : 8) Since x is greater than 2, the answer is 8, or option D in this case.

What is the output of the following program? 1: public class WaterBottle { 2: private String brand; 3: private boolean empty; 4: public static void main(String[] args) { 5: WaterBottle wb = new WaterBottle(); 6: System.out.print("Empty = " + wb.empty); 7: System.out.print(", Brand = " + wb.brand); 8: } } A. Line 6 generates a compiler error. B. Line 7 generates a compiler error. C. There is no output. D. Empty = false, Brand = null E. Empty = false, Brand = F. Empty = null, Brand = null

D. Boolean fields initialize to false and references initialize to null, so empty is false and brand is null. Brand = null is output

What is the output of the following code? 3: byte a = 40, b = 50; 4: byte sum = (byte) a + b; 5: System.out.println(sum); A. 40 B. 50 C. 90 D. The code will not compile because of line 4. E. An undefined value.

D. Line 4 generates a possible loss of precision compiler error. The cast operator has the highest precedence, so it is evaluated first, casting a to a byte. Then, the addition is evaluated, causing both a and b to be promoted to int values. The value 90 is an int and cannot be assigned to the byte sum without an explicit cast, so the code does not compile. The code could be corrected with parentheses around (a + b), in which case option C would be the correct answer.

What is the result of the following code snippet? 3: int m = 9, n = 1, x = 0; 4: while(m > n) { 5: m--; 6: n += 2; 7: x += m + n; 8: } 9: System.out.println(x); A. 11 B. 13 C. 23 D. 36 E. 50 F. The code will not compile because of line 7.

D. Prior to the first iteration, m = 9, n = 1, and x = 0. After the iteration of the first loop, m is updated to 8, n to 3, and x to the sum of the new values for m + n, 0 + 11 = 11. After the iteration of the second loop, m is updated to 7, n to 5, and x to the sum of the new values for m + n, 11 + 12 = 23. After the iteration of the third loop, m is updated to 6, n to 7, and x to the sum of the new values for m + n, 23 + 13 = 36. On the fourth iteration of the loop, m > n evaluates to false, as 6 < 7 is not true. The loop ends and the most recent value of x, 36, is output, so the correct answer is option D.

What is the result of the following? int[] random = { 6, -4, 12, 0, -10 }; int x = 12; int y = Arrays.binarySearch(random, x); System.out.println(y); A. 2 B. 4 C. 6 D. The result is undefined. E. An exception is thrown. F. The code does not compile.

D. The code compiles and runs fine. However, an array must be sorted for binarySearch() to return a meaningful result.

What is the output of the following code snippet? 3: boolean keepGoing = true; 4: int result = 15, i = 10; 5: do { 6: i--; 7: if(i==8) keepGoing = false; 8: result -= 2; 9: } while(keepGoing); 10: System.out.println(result); A. 7 B. 9 C. 10 D. 11 E. 15 F. The code will not compile because of line 8.

D. The code compiles without issue, so option F is incorrect. After the first execution of the loop, i is decremented to 9 and result to 13. Since i is not 8, keepGoing is false, and the loop continues. On the next iteration, i is decremented to 8 and result to 11. On the second execution, i does equal 8, so keepGoing is set to false. At the conclusion of the loop, the loop terminates since keepGoing is no longer true. The value of result is 11, and the correct answer is option D.

What is the result of the following statements? 6: List<String> list = new ArrayList<String>(); 7: list.add("one"); 8: list.add("two"); 9: list.add(7); 10: for(String s : list) System.out.print(s); A. onetwo B. onetwo7 C. onetwo followed by an exception D. Compiler error on line 9. E. Compiler error on line 10.

D. The code does not compile because list is instantiated using generics. Only String objects can be added to list and 7 is an int.

Given the following class in the file /my/directory/named/A/Bird.java: INSERT CODE HERE public class Bird { } Which of the following replaces INSERT CODE HERE if we compile from /my/directory? (Choose all that apply) A. package my.directory.named.a; B. package my.directory.named.A; C. package named.a; D. package named.A; E. package a; F. package A; G. Does not compile.

D. The package name represents any folders underneath the current path, which is named.A in this case. Option B is incorrect because package names are case sensitive, just like variable names and other identifiers.

What is the result of the following code? 4: int total = 0; 5: StringBuilder letters = new StringBuilder("abcdefg"); 6: total += letters.substring(1, 2).length(); 7: total += letters.substring(6, 6).length(); 8: total += letters.substring(6, 5).length(); 9: System.out.println(total); A. 1 B. 2 C. 3 D. 7 E. An exception is thrown. F. The code does not compile.

E. Line 6 adds 1 to total because substring() includes the starting index but not the ending index. Line 7 adds 0 to total. Line 8 is a problem: Java does not allow the indexes to be specified in reverse order and the code throws a StringIndexOutOf- BoundsException.

Which of the following are legal entry point methods that can be run from the command line? (Choose all that apply) A. private static void main(String[] args) B. public static final main(String[] args) C. public void main(String[] args) D. public static void test(String[] args) E. public static void main(String[] args) F. public static main(String[] args) G. None of the above.

E. Option E is the canonical main() method signature. You need to memorize it. Option A is incorrect because the main() method must be public. Options B and F are incorrect because the main() method must have a void return type. Option C is incorrect because the main() method must be static. Option D is incorrect because the main() method must be named main.

Given the following classes, what is the maximum number of imports that can be removed and have the code still compile? package aquarium; public class Water { } package aquarium; import java.lang.*; import java.lang.System; import aquarium.Water; import aquarium.*; public class Tank { public void print(Water water) { System.out.println(water); } } A. 0 B. 1 C. 2 D. 3 E. 4 F. Does not compile.

E. The first two imports can be removed because java.lang is automatically imported. The second two imports can be removed because Tank and Water are in the same package, making the correct answer E. If Tank and Water were in different packages, one of these two imports could be removed. In that case, the answer would be option D.

What is the output of the following code snippet? 3: int x = 1, y = 15; 4: while x < 10 5: y--; 6: x++; 7: System.out.println(x+", "+y); A. 10, 5 B. 10, 6 C. 11, 5 D. The code will not compile because of line 3. E. The code will not compile because of line 4. F. The code contains an infinite loop and does not terminate.

E. This is actually a much simpler problem than it appears to be. The while statement on line 4 is missing parentheses, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct answer since the loop does not use curly braces to include x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the output would be 10, 6 and option B would be correct.

What is the output of the following application? 1: public class CompareValues { 2: public static void main(String[] args) { 3: int x = 0; 4: while(x++ < 10) {} 5: String message = x > 10 ? "Greater than" : false; 6: System.out.println(message+","+x); 7: } 8: } A. Greater than,10 B. false,10 C. Greater than,11 D. false,11 E. The code will not compile because of line 4. F. The code will not compile because of line 5.

F. In this example, the ternary operator has two expressions, one of them a String and the other a boolean value. The ternary operator is permitted to have expressions that don't have matching types, but the key here is the assignment to the String reference. The compiler knows how to assign the first expression value as a String, but the second boolean expression cannot be set as a String; therefore, this line will not compile.

How many times will the following code print "Hello World"? 3: for(int i=0; i<10 ; ) { 4: i = i++; 5: System.out.println("Hello World"); 6: } A. 9 B. 10 C. 11 D. The code will not compile because of line 3. E. The code will not compile because of line 5. F. The code contains an infinite loop and does not terminate.

F. In this example, the update statement of the for loop is missing, which is fine as the statement is optional, so option D is incorrect. The expression inside the loop increments i but then assigns i the old value. Therefore, i ends the loop with the same value that it starts with: 0. The loop will repeat infinitely, outputting the same statement over and over again because i remains 0 after every iteration of the loop.

What is the output of the following code? LocalDate date = LocalDate.of(2018, Month.APRIL, 40); System.out.println(date.getYear() + " " + date.getMonth() + " " + date.getDayOfMonth()); A. 2018 APRIL 4 B. 2018 APRIL 30 C. 2018 MAY 10 D. Another date. E. The code does not compile. F. A runtime exception is thrown.

F. Java throws an exception if invalid date values are passed. There is no 40th day in April—or any other month for that matter.

Which of these compile when replacing line 8? (Choose all that apply) 7: ArrayList l = new ArrayList(); 8: // INSERT CODE HERE A. int length = l.capacity; B. int length = l.capacity(); C. int length = l.length; D. int length = l.length(); E. int length = l.size; F. int length = l.size(); G. None of the above.

F. The ArrayList class defines a method called size().

What is the output of the following code snippet? 3: int x = 4; 4: long y = x * 4 - x++; 5: if(y<10) System.out.println("Too Low"); 6: else System.out.println("Just right"); 7: else System.out.println("Too High"); A. Too Low B. Just Right C. Too High D. Compiles but throws a NullPointerException. E. The code will not compile because of line 6. F. The code will not compile because of line 7.

F. The code does not compile because two else statements cannot be chained together without additional if-then statements, so the correct answer is option F. Option E is incorrect as Line 6 by itself does not cause a problem, only when it is paired with Line 7. One way to fix this code so it compiles would be to add an if-then statement on line 6. The other solution would be to remove line 7.

What is the result of the following code? 2: String s1 = "java"; 3: StringBuilder s2 = new StringBuilder("java"); 4: if (s1 == s2) 5: System.out.print("1"); 6: if (s1.equals(s2)) 7: System.out.print("2"); A. 1 B. 2 C. 12 D. No output is printed. E. An exception is thrown. F. The code does not compile.

F. The question is trying to distract you into paying attention to logical equality versus object reference equality. It is hoping you will miss the fact that line 4 does not compile. Java does not allow you to compare String and StringBuilder using ==.

What is the result of the following code? StringBuilder b = "rumble"; b.append(4).deleteCharAt(3).delete(3, b.length() - 1); System.out.println(b); A. rum B. rum4 C. rumb4 D. rumble4 E. An exception is thrown. F. The code does not compile.

F. This is a trick question. The first line does not compile because you cannot assign a String to a StringBuilder. If that line were StringBuilder b = new StringBuilder("rumble"), the code would compile and print rum4. Watch out for this sort of trick on the exam. You could easily spend a minute working out the character positions for no reason at all.

What is the result of the following code? (Choose all that apply) 13: String a = ""; 14: a += 2; 15: a += 'c'; 16: a += false; 17: if ( a == "2cfalse") System.out.println("=="); 18: if ( a.equals("2cfalse")) System.out.println("equals"); A. Compile error on line 14. B. Compile error on line 15. C. Compile error on line 16. D. Compile error on another line. E. == F. equals G. An exception is thrown.

F. a += 2 expands to a = a + 2. A String concatenated with any other type gives a String. Lines 14, 15, and 16 all append to a, giving a result of "2cfalse". The if statement on line 18 returns false because the values of the two String objects are the same using object equality. The if statement on line 17 returns false because the two String objects are not the same in memory. One comes directly from the string pool and the other comes from building using String operations.

What is output by the following code? (Choose all that apply) 1: public class Fish { 2: public static void main(String[] args) { 3: int numFish = 4; 4: String fishType = "tuna"; 5: String anotherFish = numFish + 1; 6: System.out.println(anotherFish + " " + fishType); 7: System.out.println(numFish + " " + 1); 8: } } A. 4 1 B. 41 C. 5 D. 5 tuna E. 5tuna F. 51tuna G. The code does not compile.

G. Line 5 does not compile. This question is checking to see if you are paying attention to the types. numFish is an int and 1 is an int. Therefore, we use numeric addition and get 5. The problem is that we can't store an int in a String variable. Supposing line 5 said String anotherFish = numFish + 1 + "";. In that case, the answer would be options A and D. The variable defined on line 5 would be the string "5", and both output statements would use concatenation.

Which of the following are true? (Choose all that apply) A. A local variable of type boolean defaults to null. B. A local variable of type float defaults to 0. C. A local variable of type Object defaults to null. D. A local variable of type boolean defaults to false. E. A local variable of type boolean defaults to true. F. A local variable of type float defaults to 0.0. G. None of the above.

G. Option G is correct because local variables do not get assigned default values. The code fails to compile if a local variable is not explicitly initialized. If this question were about instance variables, options D and F would be correct. A boolean primitive defaults to false and a float primitive defaults to 0.0.

Summary In this chapter, you saw that Java classes consist of members called fi elds and methods. An object is an instance of a Java class. There are three styles of comment: a single-line comment (//), a multiline comment (/* */), and a Javadoc comment (/** */). Java begins program execution with a main() method. The most common signature for this method run from the command line is public static void main(String[] args). Arguments are passed in after the class name, as in java NameOfClass firstArgument. Arguments are indexed starting with 0. Java code is organized into folders called packages. To reference classes in other packages, you use an import statement. A wildcard ending an import statement means you want to import all classes in that package. It does not include packages that are inside that one. java.lang is a special package that does not need to be imported. Constructors create Java objects. A constructor is a method matching the class name and omitting the return type. When an object is instantiated, fi elds and blocks of code are initialized fi rst. Then the constructor is run. Primitive types are the basic building blocks of Java types. They are assembled into reference types. Reference types can have methods and be assigned to null. In addition to "normal" numbers, numeric literals are allowed to begin with 0 (octal), 0x (hex), 0X (hex), 0b (binary), or 0B (binary). Numeric literals are also allowed to contain underscores as long as they are directly between two other numbers. Declaring a variable involves stating the data type and giving the variable a name. Variables that represent fi elds in a class are automatically initialized to their corresponding "zero" or null value during object instantiation. Local variables must be specifi cally initialized. Identifi ers may contain letters, numbers, $, or _. Identifi ers may not begin with numbers.

Scope refers to that portion of code where a variable can be accessed. There are three kinds of variables in Java, depending on their scope: instance variables, class variables, and local variables. Instance variables are the nonstatic fi elds of your class. Class variables are the static fi elds within a class. Local variables are declared within a method. For some class elements, order matters within the fi le. The package statement comes fi rst if present. Then comes the import statements if present. Then comes the class declaration. Fields and methods are allowed to be in any order within the class. Garbage collection is responsible for removing objects from memory when they can never be used again. An object becomes eligible for garbage collection when there are no more references to it or its references have all gone out of scope. The finalize() method will run once for each object if/when it is fi rst garbage collected. Java code is object oriented, meaning all code is defi ned in classes. Access modifi ers allow classes to encapsulate data. Java is platform independent, compiling to bytecode. It is robust and simple by not providing pointers or operator overloading. Finally, Java is secure because it runs inside a virtual machine.

This chapter covered a wide variety of topics, including dozens of Java operators, along with numerous control fl ow statements. Many of these operators and statements may have been new to you. It is important that you understand how to use all of the required Java operators covered in this chapter and know how operator precedence infl uences the way a particular expression is interpreted. There will likely be numerous questions on the exam that appear to test one thing, such as StringBuilder or exception handling, when in fact the answer is related to the misuse of a particular operator that causes the application to fail to compile. When you see an operator on the exam, always check that the appropriate data types are used and that they match each other where applicable. For statements, this chapter covered two types of control structures: decision-making controls structures, including if-then, if-then-else, and switch statements, as well as repetition control structures including for, for-each, while, and do-while. Remember that most of these structures require the evaluation of a particular boolean expression either for branching decisions or once per repetition. The switch statement is the only one that supports a variety of data types, including String variables as of Java 7.

With a for-each statement you don't need to explicitly write a boolean expression, since the compiler builds them implicitly. For clarity, we referred to an enhanced for loop as a for-each loop, but syntactically they are written as a for statement. We concluded this chapter by discussing advanced control options and how fl ow can be enhanced through nested loops, break statements, and continue statements. Be wary of questions on the exam that use nested statements, especially ones with labels, and verify they are being used correctly. This chapter is especially important because at least one component of this chapter will likely appear in every exam question with sample code. Many of the questions on the exam focus on proper syntactic use of the structures, as they will be a large source of questions that end in "Does not compile." You should be able to answer all of the review questions correctly or fully understand those that you answered incorrectly before moving on to later chapters.


Related study sets

Psychology: Divisions of Nervous System

View Set

Chapter 9: Time Management in Nursing

View Set

Chapter 13: Moral Development, Values, and Religion,

View Set