Instance variables are also known as; a) local variables b) instances variable c) fields d) Both b and c d) Both b and c. Instance variables are also known as fields.  Instance variables are declared in classes and are typically manipulated by the methods of the class they belong to.  Each object of a class maintains a separate instance of these kinds of variables. Variables declared in the body of a method are known as;  a) local variables b) instances variable c) fields d) Both b and c a) local variables Variables that are declared within the body of a method are known as local variables. In general, it is best to make __________ private and _______________ public in order to incorporate data hiding. a) methods, instance variables b) instance variables, methods c) instance variables, fields d) methods, local variables b) instance variables, methods Precede each field and method declaration with an access modifier.  Generally, instance variables should be declared private and methods public.  In some cases it is also appropriate to make methods private in cases where they are only used by other methods of the same class. There are 3 ways to return control to a statement that calls a method.  What are they? 1. Right brace at end of method when no return is required (void) 2. return; statement is encountered 3. return expression; statement is encountered True/False:  By default, the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor. True. By default, the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor.    When this happens, all of the instance variables are set to a default value. True/False:  In Java it is possible to have many classes in every .java file. False. You can only have one public class in each Java file. Method headers contain all of the following except:        a) Access modifier        b) Left brace        c) Name of method        d) Return type b) Left brace  Every method body is is delimited by left and right braces. Every Java application is composed of at least one:        a) local variable        b) instance variable        c) public class declaration        d) imported class c) public class declaration (textbook page 40) A class instance creation expression contains:         a) Parentheses        b) The new keyword        c) The name of the class        d) All of the above d) All of the above (Textbook page 74 & 86) Calling a method of another object requires which item?        a) The dot separator        b) Open and close braces        c) The new keyword        d) None of the above a) The dot separator What is the default initial value of a String instance variable?        a) ""        b) "default"        c) default        d) null d) null (textbook page 82) Each class declaration that begins with the keyword ________ must be stored in a file that has exactly the the same name and ends with the .java file extension. public Keyword __________ in a class declaration is followed immediately by a classes name. class Keyword __________ requests memory from the system to store an object, then calls the corresponding class's constructor to initialize the object. new Each parameter must specify both a __________ and a ____________. Each parameter must specify both a ____type___   and a _____name_____. By default, classes that are compiled in the same directory are considered to be in the same package known as the _____________________. default package By default, classes that are compiled in the same directory are considered to be in the same package known as the _default_package_______. When each object of a class maintains its own copy of an attribute, the field that represents the attribute is also known as a __________________. instance variable When each object of a class maintains its own copy of an attribute, the field that represents the attribute is also known as a _instance_variable_. Java provides two primitive types for storing floating-point numbers in memory; ____________  and ____________. float, double Java provides two primitive types for storing floating-point numbers in memory; _float_  and _double___. Variables of type double represent __________ floating-point numbers. double-precision Variables of type double represent _double-precision__ floating-point numbers. Scanner method ______________ returns a double value. nextDouble Scanner method _nextDouble__ returns a double value. Keyword public is an access ___________. modifier Keyword public is an access _modifier__. Return type ____________ indicates that a method will not return a value. void Return type _void__ indicates that a method will not return a value. Scanner method ____________ reads characters until it encounters a newline character, then returns those characters as a string. nextLine Scanner method _nextLine__ reads characters until it encounters a newline character, then returns those characters as a string. Class string is in package _________________. java.lang Class string is in package _java.lang___. An _________________________ is not required if you always refer to a class with it's fully qualified class name. import declaration An _import declaration__ is not required if you always refer to a class with it's fully qualified class name. A _________________________ is a number with a decimal point, such as 7.33, 0.0975 or 1000.12345. floating-point number A _floating-point_number__ is a number with a decimal point, such as 7.33, 0.0975 or 1000.12345. Variables of type float represent _________________ floating-point numbers. single-precision Variables of type float represent _single-precision__ floating-point numbers. The format specifier ______________________ is used to output values of type float or type double. %f The format specifier ____%f___ is used to output values of type float or type double. Types in Java are divided into two categories; ____________ types and ______________ types. primitive, reference Types in Java are divided into two categories; _primitive_ types and _reference_ types. What is the difference between a local variable and a field? Local variables are declared within methods while fields (also known as instance variables) are declared within classes.  A local variable can only be used within the method where it is declared while an instance variable is available to all methods within the class in which it is declared. True/False:   By convention, method names begin with an uppercase first letter. False.  By convention, method names begin with a lowercase first letter and then use 'camel back' form where all subsequent words in the name begin with a capital first letter such as; nextLine. True/False:   An import declaration is not required when one class in a package uses another in the same package. True. Classes within the same package can implicitly call each other without imports. True/False:   Empty parentheses following a method name in a method declaration indicate that the method does not require any parameters to perform it's task. True True/False:   Variables or methods declared with access modifier private are accessible only to methods of the class in which they're declared. True True/False:   A primitive-type variable can be used to invoke a method. False A primitive-type variable cannot be used to invoke a method.  A reference to an object is required to invoke the objects methods as in; GradeBook myGradeBook = new GradeBook();   Where myGradeBook is a reference variable that refers to a GradeBook object.  (Textbook page 84). True/False:   Variables declared in the body of a particular method are known as instance variables and can be used in all methods of the class. False Such variables declared in the body of a method are called local variables however they can only be used within the method in which they are declared. True/False:   Every methods body is delimited by left and right curly braces {}. True The method body is delimited by the left and right curly brace {}. Method headers contain an access modifier, the name of the method and a Return type.  The curly braces are not considered to be part of the method header. True/False:  Primitive type local variables are initialized by default. False Primitive type instance variables are initialized by default. Each local variable must be explicitly assigned a value. True/False:  Reference-type instance variables are initialized by default to the value null. True True/False:  Any class that contains; public static void main(String[] args) can be used to execute an application. True True/False:  The number of arguments in the method call must match the number of parameters in the method declarations parameter list. True True/False:  Floating-point values that appear in source code are known as floating-point literals and are type float by default. False Such literals are of type double by default.  (Textbook page 88). A method is invoked with a _________________. method call A method is invoked with a _method_call_. A variable known only within the method in which it is declared is called a __________________. local variable A variable known only within the method in which it is declared is called a _local_variable__. The ______________ statement in a call method can be used to pass the value of an expression back to the calling method. return  The _return_ statement in a call method can be used to pass the value of an expression back to the calling method. The keyword _______________ indicates that a method does not return a value. void The keyword _void__ indicates that a method does not return a value. Data can be added or removed only from the _______________ of a stack. top Data can be added or removed only from the _top__ of a stack. Stacks are known as ___________________ data structures. LIFO  Last-In, First-out Stacks are known as _last-in,_first-out_(LIFO)_ data structures; the last item pushed (inserted) on the stack is the first item popped (removed) from the stack. The three ways to return control from a called method to a caller are ______________, ___________________ and ________________. return; or return expression; or encountering the closing right brace of a method.  The three ways to return control from a called method to a caller are _return;_, __return_expression;__ and _encountering_the_closing_right_brace_of_a_method_. An object of class ____________ produces random numbers. Random An object of class _Random__ produces random numbers. The program-execution stack contains the memory for local variables on each invocation of a method during a program's execution.  This data, stored as a portion of the program-execution stack, is known as the ____________ or ______________ of the method call. activation record or stack frame The program-execution stack contains the memory for local variables on each invocation of a method during a program's execution.  This data, stored as a portion of the program-execution stack, is known as the _activation_record_ or _stack_frame_ of the method call. If there are more method calls than can be stored on the program-execution stack, an error known as a ______________________ occurs. stack overflow If there are more method calls than can be stored on the program-execution stack, an error known as a _stack_overflow_ occurs. The _________________ of a declaration is the portion of a program that can refer to the entity in the declaration by name. scope The _scope_ of a declaration is the portion of a program that can refer to the entity in the declaration by name. (Textbook page 219-220). It's possible to have several methods with the same name that each operate on different types or numbers of arguments.  This feature is called method _____________. overloading It's possible to have several methods with the same name that each operate on different types or numbers of arguments.  This feature is called method _overloading_. (Textbook Page 222). The program execution-stack is also referred to as the _____________ stack. method call The program execution-stack is also referred to as the _method_call_ stack. Lists and tables of values can be stored in _________________. arrays Lists and tables of values can be stored in _arrays_. An array is a group of ________________ (called elements or components) containing values that all have the same ______________. variables, type An array is a group of _variables_ (called elements or components) containing values that all have the same _type_. The ______________ allows you to iterate through the elements in n array without using  counter. enhanced for statement The _enhanced_for_statement_ allows you to iterate through the elements in n array without using  counter.  ie; for (parameter : arrayName)                      statement (Textbook page 258). The number used to refer to a particular array element is called the element's ______________. index The number used to refer to a particular array element is called the element's _index_. An array that uses two indices is referred to as a _________________ array. two dimensional An array that uses two indices is referred to as a _two_dimensional_ array. Use the enhanced for statement ____________________ to walk through double array numbers. for (double d : numbers) Use the enhanced for statement _for_(double_d_:_numbers)_ to walk through double array numbers. Command-line arguments are stored in _______________. an array of Strings, called args by convention Command-line arguments are stored in _an_array_of_Strings,_called_args_by_convention_. Use the expression ___________________ to receive the total number of arguments in a command line. Assume that the command line arguments are stored in String[] args. args.length Use the expression _args.length_ to receive the total number of arguments in a command line. Assume that the command line arguments are stored in String[] args. Given the command java MyClass test, the first command-line argument is __________________. test Given the command java MyClass test, the first command-line argument is _test_. An __________ in the parameter list of a method indicates that the method can receive a variable number of arguments. ellipsis (...) An _ellipsis_(...)_ in the parameter list of a method indicates that the method can receive a variable number of arguments. True/False:  An array can store many different types of values. False. An array can only store values of the same type. True/False:  An array index should normally be of type float. False An array index must be an integer or an integer expression. True/False:  An individual array element that's passed to a method and modified in that method will contain the modified value when the called method completes execution. False for individual primitive-type elements of an array. A called method receives and manipulates a copy of the value of such an element, so modifications do not affect the original value. If the reference of an array is passed to a method, however, modifications to the array elements made in the called method are indeed reflected in the original. True/False:  Command-line arguments are separated by commas. False Command-line arguments are separated by white space. Collections of related data items are known as _______________________. data structures Collections of related data items are known as _data_structures_. (Textbook page 241). ArrayLists are similar to arrays but provide additional functionality such as ______________________. dynamic resizing ArrayLists are similar to arrays but provide additional functionality such as _dynamic_resizing_. Arrays are objects so they are considered __________________ types. reference Arrays are objects so they are considered _reference_ types. (Textbook page 242) When compiling a class in a package, the javac command-line option ______________ specifies where to store the package and causes the compiler to create the package's directories if they do not exist. -d When compiling a class in a package, the javac command-line option _-d_ specifies where to store the package and causes the compiler to create the package's directories if they do not exist. String class static method ________________ is similar to method System.out.printf, but returns a formatted String rather than displaying a String in a command window. format String class static method _format_ is similar to method System.out.printf, but returns a formatted String rather than displaying a String in a command window. (TextBook Page 314). If a method contains a local variable with the same name as one of it's class's fields, the local variable ______________ the field in that method's scope. shadows If a method contains a local variable with the same name as one of it's class's fields, the local variable _shadows_ the field in that method's scope. The _____________ method is called by the garbage collector just before it reclaims an object's memory. finalize The _finalize_ method is called by the garbage collector just before it reclaims an object's memory. A _______________ declaration specifies one class to import. single-type import A _single-type_import_ declaration specifies one class to import. If a class declares constructors, the compiler will not create a _________________. default constructor If a class declares constructors, the compiler will not create a _default_constructor_. An object's _________________ method is called implicitly when an object appears in code where a String is needed. toString An object's _toString_ method is called implicitly when an object appears in code where a String is needed. (Textbook page 314). Get methods are commonly called _________ or ____________. accessor methods, query methods Get methods are commonly called _accessor_methods_ or _query_methods_. A _______________ method tests whether a condition is true or false. predicate A _predicate_ method tests whether a condition is true or false. For every enum, the compiler generates a static method called __________________ that returns an array of the enum's constants in the order in which they were declared. values For every enum, the compiler generates a static method called _values_ that returns an array of the enum's constants in the order in which they were declared. Composition is sometimes referred to as an ______________ relationship. has-a Composition is sometimes referred to as an _has-a_ relationship.   It should be noted that in some textbooks this 'has-a' relationship is referred to as 'is-like' relationship.  The other kind of relationship in Java is the 'is-a' relationship. An _____________________ declaration contains a comma-separated list of constants. enum An _enum_ declaration contains a comma-separated list of constants. A _________________ variable represents classwide information that' shared by all the objects of the class. static A _static_ variable represents classwide information that' shared by all the objects of the class. A _____________________ declaration imports one static member. single static import A _single_static_import_ declaration imports one static member. The _________________________________ states that code should be granted only the amount of privilege and access it that it needs to accomplish it's designated task. principle of least privilege The _principle_of_least_privilege_ states that code should be granted only the amount of privilege and access it that it needs to accomplish it's designated task. Keyword ______________ specifies that a variable is not modifiable. final Keyword _final_ specifies that a variable is not modifiable. There can be only one _____________________ in a Java source-code file, and it must precede all over declarations and statements in that file. package declaration There can be only one _package_declaration_ in a Java source-code file, and it must precede all other declarations and statements in that file. A _________________ declaration imports only the classes that the program uses from a particular package. type-import-on-demand A _type-import-on-demand_ declaration imports only the classes that the program uses from a particular package. The compiler uses a ___________________ to locate the classes it needs in it's classpath. class loader The compiler uses a _class_loader_ to locate the classes it needs in it's classpath. The classpath for the compiler and JVM can be specified with the _________________ option to the javac or java command, or by setting the ______________ environment variable. -classpath, CLASSPATH The classpath for the compiler and JVM can be specified with the _-classpath_ option to the javac or java command, or by setting the _CLASSPATH_ environment variable. Set methods are commonly called _____________________ because they typically change a value. mutator methods Set methods are commonly called _mutator_methods_ because they typically change a value. A ___________________ imports all static members of a class. static import on demand A _static_import_on_demand_ imports all static members of a class. The public methods of a class are also known as the class's __________________ or ________________. public services, public interface The public methods of a class are also known as the class's _public_services_ or _public_interface_. (Textbook Page 312). Classes simplify programming, because the client can use only the __________________ methods exposed by the class. public Classes simplify programming, because the client can use only the _public_ methods exposed by the class. Such methods are usually client oriented rather than implementation oriented.  Clients are neither aware of, nor involved in, a class's implementation. Clients generally care about what a class does and not how it does it.  (Textbook page 316). An attempt by a method that's not a member of a class to access a private member of that class is called a _______________________. compilation error An attempt by a method that's not a member of a class to access a private member of that class is called a _compilation_error_. (Textbook page 317). The company that popularized personal computing was _________________. Apple The company that popularized personal computing was _Apple_. The computer that made personal computing legitimate in business and industry was the _____________________. IBM Personal Computer The computer that made personal computing legitimate in business and industry was the _IBM_Personal_Computer_. Computers process data under the control of sets of instructions called __________________. programs Computers process data under the control of sets of instructions called _programs_. The key logical units of the computer are the ________, ________, __________, ________, _________ and _________. input unit, output unit, memory unit, central processing unit, arithmetic and logic unit, secondary storage unit  The key logical units of the computer are the _input_unit_, _output_unit_, _memory_unit, _central_processing_unit_, _arithmetic_and_logic_unit_ and _secondary_storage_unit_. The three types of languages discussed in chapter one are _____________, ____________ and ______________. machine language, assembly languages, high-level languages The three types of languages discussed in chapter one are _machine_language_, _assembly_languages_ and _high-level_languages_. The programs that translate high-level language programs into machine language are called __________________. compilers The programs that translate high-level language programs into machine language are called _compilers_. ________________ is a smartphone operating system based on the Linux kernel and Java. Android _Android_ is a smartphone operating system based on the Linux kernel and Java. ____________ software is generally feature complete and (supposedly) bug-free, and ready for use by the community. release candidate _Release_candidate_ software is generally feature complete and (supposedly) bug-free, and ready for use by the community. The Wii remote, as well as many smartphones, use an ________________ which allows the device to respond to motion. accelerometer The Wii remote, as well as many smartphones, use an _accelerometer_ which allows the device to respond to motion. The ____________ command from the JDK executes a Java application. java The _java_ command from the JDK executes a Java application. The ____________ command from the JDK compiles a Java program. javac The _javac_ command from the JDK compiles a Java program. A java program file must end with the _____________ file extension. .java A java program file must end with the _.java_ file extension. When a Java program is compiled, the file produced by the compiler ends with the _____________ file extension. .class When a Java program is compiled, the file produced by the compiler ends with the _.class_ file extension. The file produced by the Java compiler contains __________________ that are executed by the Java Virtual Machine (JVM). bytecodes The file produced by the Java compiler contains _bytecodes_ that are executed by the Java Virtual Machine (JVM). Objects have the property of _______________________ - although objects may know how to communicate with one another across well-defined interfaces, they normally are not allowed to know how other objects are implemented. information hiding Objects have the property of _information_hiding_ - although objects may know how to communicate with one another across well-defined interfaces, they normally are not allowed to know how other objects are implemented.  (Information hiding is also known as data hiding or encapsulation). The property of encapsulation is also known as __________________ or _________________. information hiding, data hiding The property of encapsulation is also known as _information_hiding_ or _data_hiding_. (Textbook page 81). Java programmers concentrate on creating ____________________, which contain fields and the set of methods that manipulate those fields and provide services to clients. classes Java programmers concentrate on creating _classes_, which contain fields and the set of methods that manipulate those fields and provide services to clients. The process of analyzing and designing a system from an object-oriented point of view is called _____________________. OOAD  Object Oriented Analysis and Design The process of analyzing and designing a system from an object-oriented point of view is called _OOAD,_Object_Oriented_Analysis_and_Design_. In a class containing methods with the same name, the methods are distinquished by; Number of arguments Types of arguments Return type Number of arguments and Types of arguments Types of arguments and Return type Number of arguments and Types of arguments (Textbook page 222) Consider the following Java statements:  int x = 9; double y = 5.3; result = calculateValue( x, y ); Which of the following statements is true?  A. A method is called with its name and parentheses. B. x and y are parameters. C. Copies of x and y are passed to the method calculateValue(). D. x and y are arguments. a. None of the statements are true. b. B and D are true. c. B is false. d. All of the statements are true. c. B is false. x and y are arguments. Parameters specified in a method's declaration. They indicate the types of the arguments passed to the method when it is called. A JButton can cause an event (i.e., a call to an event-handling method) if: a. An event handler has been called. b. The registered event handler implements the ActionListener interface. c. The registered event handler extends the GUI. d. The JButton has been added to JApplet. b. The registered event handler implements the ActionListener interface. Which of these statements best defines scope? a. Scope refers to the classes that have access to a variable. b. Scope determines whether a variable’s value can be altered. c. Scoping allows the programmer to use a class without using its fully qualified name. d. Scope is the portion of a program that can refer to an entity by name. d. Scope is the portion of a program that can refer to an entity by name. Which of the following does not contribute to improved software reusability? * Quickly creating new class libraries without testing them thoroughly * Licensing schemes and protection mechanisms * Descriptions of classes that allow programmers to determine whether a class fits their needs * Cataloging schemes and browsing mechanisms My initial guess: * Licensing schemes and protection mechanisms But remember that I got 3 out of 5 wrong so at least 3 of my answers are the wrong one. Information is passed to a method in:  a. the method name. b. that method's return. c. the called method. d. the arguments to the method. d. the arguments to the method. Programs designed for maintainability are constructed from small simple pieces or modules. Modules in Java are called: a. methods. b. classes. c. arguments. d. both methods and classes. d. both methods and classes. A well-designed method; a. performs multiple unrelated tasks. b. repeats code found in other methods. c. contains thousands of lines of code. d. performs a single, well-defined task. d. performs a single, well-defined task. Which of the following methods is not in the Math class? a. ceil b. abs c. parseInt d. log c. parseInt parseInt is in the Integer class. Which of the following can be an argument in a method? a. Constants. b. Variables. c. Expressions. d. All of the above. d. All of the above. Method log takes the logarithm of its argument with respect to what base? a. 10 b. e c. 2 d. pi b. e Swing GUI components typically are attached to; a. a JApplet. b. a content pane. c. an init method. d. a JTextArea. b. a content pane. Variables should be declared as fields if; a. they are local variables.  b. they are used only within a method. c. their values must be saved between calls to the method. d. they are arguments. c. their values must be saved between calls to the method. Which of the following tasks cannot be performed using an enhanced for loop? a. multiplying all the values in an array together b. displaying all even element values in an array c. comparing the elements in an array to a specific value d. incrementing the value stored in each element of the array d. incrementing the value stored in each element of the array The parameter list in the method header and the method call arguments must agree in: a. number b. type c. order d. all of the above d. all of the above Which of the following promotions of primitive types is NOT allowed to occur? a. char to int. b. int to double. c. short to long. d. double to float. d. double to float. Which of the following primitive types is never promoted to another type? a. double. b. byte. c. boolean. d. Both a (double) and c. (boolean) d. Both a (double) and c. (boolean) Which statement is not true. a. The Java API consists of packages. b. The Java API is provided to keep programmers from "reinventing the wheel." c. The Java API consists of import declarations. d. The class javax.swing.JApplet is part of the Java API. c. The Java API consists of import declarations. (The Java API is built from packages.) Which of the following is not a package in the Java API? a. java.component. b. java.awt. c. javax.swing.event. d. java.lang. a. java.component. The java.text package contains classes for manipulating all of the following items except; a. classes b. numbers c. strings d. characters a. classes Which statement below could be used to simulate the outputs of tossing a quarter to get heads or tails? a. 1 + (int) ( Math.random() * 6 ); b. 1 + (int) ( Math.random() * 2 ); c. 6 + (int) ( Math.random() * 1 ); d. 1 + (int) ( Math.random() * 25 ); b. 1 + (int) ( Math.random() * 2 ); The purpose of (int) in the statement 1 + (int) (Math.random() * 6); a. is to create an element of chance. b. is to be a scaling factor. c. is to shift the output value. d. is to truncate the floating-point part of the product. d. is to truncate the floating-point part of the product. Method random generates a random double value in the range from 0.0; a. up to but not including 1.0 b. up to and including 1.0 c. up to and including 100.0 d. up to but not including 100.0 a. up to but not including 1.0 An applet's content pane may be assigned a layout manager to: a. Handle events. b. Arrange GUI components. c. Implement interfaces. d. Create GUI components. b. Arrange GUI components. Which of the following is false? a. A static method must be used to access private static instance variables b. A static method has no this reference c. A static method can be accessed even when no objects of its class have been instantiated d. A static method can call instance methods directly d. A static method can call instance methods directly What keyword declares that a variable is a constant? a. constant b. static c. private d. final d. final Identifiers in Java have ________ and ________ scopes? a. method, class. b. class, block. c. block, statement. d. statement, file. b. class, block. Which of the following statements describes block scope? a. It begins at the opening { of the class declaration and terminates at the closing } b. It limits label scope to only the method in which it is declared. c. It begins at the identifier's declaration and ends at the terminating right brace (}). d. It is valid for one statement only. c. It begins at the identifier's declaration and ends at the terminating right brace (}). Java programmers do not focus on: a. Crafting new classes and reusing existing classes b.  Understanding class library implementations c. Carefully testing classes they design d. Carefully documenting classes they design My guess: b.  Understanding class library implementations The key methods of the class JApplet are: a. init, start, paint, stop, destroy, quit. b. init, start, paint, stop, destroy, restart. c. init, start, paint, stop, destroy. d. init, start, repaint, stop, destroy. c. init, start, paint, stop, destroy. The repaint method is necessary because: a. paint can only be called once. b. repaint provides context (i.e. a Graphics argument) to paint. c. paint can only be called from init. d.None of the above. b. repaint provides context (i.e. a Graphics argument) to paint. Redefining one of the JApplet methods is also known as; a. overriding. b. overloading c. hiding d. initializing a. overriding. In a class containing methods with the same name, the methods are distinguished by: a. Number of arguments. b. Types of arguments. c. Return type. d. A and B. e. B and C. d. A and B. A Java class can have which of the following methods? A. foo( int a ) B. foo( int a, int b )  C. foo( double a ) D. foo( double a, double b ) E. foo( int b ) a. All of the above. b. A, B, D, E. c. A, B, C, D. d. A, C, D, E. c. A, B, C, D. An overloaded method is one that; a. has a different name as another method, but the same arguments. b. has the same name as another method, but different arguments. c. has the same name and arguments as a method defined in another class. d. has the same name and arguments, but a different return type as another method. b. has the same name as another method, but different arguments. A recursive method;  a. calls itself directly or indirectly. b. has a base case c. has a recursive call (or recursion step) d. All of the above. d. All of the above. The Java primitive type that holds numbers with the largest absolute value is: a. double. b. float. c. long. d. int. a. double. Which of the following statements about recursion are true; a. Recursion uses repetition by having a method call itself. b. Recursion uses a termination test. c. Recursion can occur infinitely. d. All of the above. e. None of the above. d. All of the above. The recursion step should; a. check for the base case. b. call a fresh copy of the recursive method to work on a smaller problem. c. make two calls to the recursive method. d. iterate until it reaches a termination condition. b. call a fresh copy of the recursive method to work on a smaller problem. The number of calls to the fibonacci method to calculate fibonacci(7) is: a. 7 b. 13 c. 41 d. 39 c. 41 Operands in Java are evaluated; a. right to left. b. left to right. c. at the same time. d. determined at runtime. b. left to right. Recursion is often less efficient than iteration because; a. it can cause an explosion of method calls. b. it is not as intuitive. c. recursive methods are harder to debug. d. recursive methods take longer to program. a. it can cause an explosion of method calls. All of the following are true for both recursion and iteration except; a. they have a base case. b. they can cause infinite loops. c. they are based on a control statement. d. both gradually approach termination. a. they have a base case. Recursion often is preferable over iteration because; a. it is faster. b. it requires less memory. c. it models the program more logically. d. all of the above. c. it models the program more logically. Which of the following statements about arrays are true? A. Arrays are a group of variables containing values that all have the same type. B. Elements are located by index or subscript. C. The length of array c is determined by the expression c.length(); D. The seventh element of array c is specified by c[7]. a. A, C, D. b. A, B. c. C, D. d. A, B, C, D. b. A, B. Statements C and D are false. The length of array c is determined by c.length, and the seventh element of array c is specified by c[6] because index start at 0. Object-Oriented Programming encapsulates: a.Data and methods. b.Information hiding. c.Classes. d.Adjectives a.Data and methods. If class A extends B, then: a. Class A is the base class. b. Class A is the superclass. c. Class A inherits from class B. d. Class B is the derived class. c. Class A inherits from class B.   Class B is the base class or superclass. Class A is the derived class or subclass. Constructors: a. Have the same name as the class. b. May not specify a return type. c. Initialize objects of a class. d. All of the above. d. All of the above. An instance variable is hidden in the scope of a method when; a. The instance variable has the same name as the method. b. The instance variable has the same name as a local variable in the method. c. The instance variable has the same name as the class. d. The instance variable has the same name as the file. b. The instance variable has the same name as a local variable in the method. Which of the following statements is true? a. Within a class’s scope, class members are accessible to all of that class’s methods, but cannot be referenced directly by name. b. It is a syntax error if a method declares a local variable with the same name as a variable declared in the method’s enclosing class. c. Variables declared in a method are known only to that method. d. None of the above. c. Variables declared in a method are known only to that method. Which of the following should usually be private? a. Methods. b. Constructors. c. Variables (or fields). d. All of the above. c. Variables (or fields). Which of the following statements is true? a. Methods and instance variables can both be either public or private. b. Information hiding is achieved by restricting access to class members via keyword public. c. The private members of a class are directly accessible to the client of a class. d. None of the above is true. a. Methods and instance variables can both be either public or private. When should a program explicitly use the this reference: a. Accessing a private variable. b. Accessing a public variable. c. Accessing a local variable. d. Accessing a field that is shadowed by a local variable. d. Accessing a field that is shadowed by a local variable. Having a this reference allows: a. A method refer explicitly to the instance variables and other methods of the object on which the method was called. b. A method to refer implicitly to the instance variables and other methods of the object on which the method was called. c. An object to reference itself. d. All of the above. d. All of the above. A constructor cannot: a. Be overloaded. b. Initialize variables to their defaults. c. Specify return types or return values. d. Have the same name as the class. c. Specify return types or return values. Which of the following will be used to create an instance of a class if the programmer does not define a constructor? a. A default constructor. b. An overloaded constructor. c. The Object class constructor with the name of the desired class passed in as an argument. d. If no constructor is written, then one isn’t needed. a. A default constructor. Constructors: a. Initialize instance variables. b. When overloaded, can have identical argument lists. c. When overloaded, are selected by number and types of parameters. d. a and c. d. a and c. A well-designed group of constructors: a. Guarantee the object is created in a consistent state. b. May call common methods. c. Allows the class's user flexibility in specifying some or all of the initial instance variable values. d. All of the above. d. All of the above. Not using set and get methods is: a. A syntax error. b. A logic error. c. Not good program design. d. None of the above. c. Not good program design. Using public set methods provides data integrity if: a. The instance variables are public. b. The instance variables are private. c. The programmer provides validity checking. d. Both b and c. d. Both b and c. Composition: a. Is a form of software reuse. b. Is using an object reference as a class member. c. Is a good design practice. d. All of the above. d. All of the above. Which of the following is not true? a. Finalizer methods typically return resources to the system. b. Memory leaks using Java are rare because of garbage collection. c. Objects are marked for garbage collection by the finalizer. d. The garbage collector reclaims unused memory. c. Objects are marked for garbage collection by the finalizer. Objects are marked for garbage collection when there are no more references to the object. Static class variables: a. Are final. b. Are public. c. Are private. d. Are shared by all objects of a class. d. Are shared by all objects of a class. Which of the following is not true? a. A static method must be used to access private static instance variables. b. A static method has no this reference. c. A static method can be accessed even when no objects of its class have been instantiated. d. A static method can call instance methods directly. d. A static method can call instance methods directly. Instance variables declared final do not or cannot: a. Use the principle of least privilege. b. Be initialized. c. Be modified. d. Cause syntax errors if used as a left-hand value. c. Be modified. A package is: a. A directory structure used to organize classes and interfaces.  b. A mechanism for software reuse. c. A group of related classes and interfaces. d. All of the above. d. All of the above. A class within a package must be declared public if; a. It will only be used by other classes in the same package. b. It will be used by classes that are not in the same package. c. It is in the same directory as the other classes in the package. d. It has a unique name. b. It will be used by classes that are not in the same package. Classes outside the package cannot use a class if the class is not declared public. Consider the statement package com.deitel.jhtp5.ch08; a. The statement declares a package that exists at deitel.com. b. The statement uses the Sun Microsystems convention of package naming. c. The statement specifies a package that can be imported using: import com.deitel.ch08. d. The statement will generate a compile time error. b. The statement uses the Sun Microsystems convention of package naming. When no member access modifier is specified for a method or variable, the method or variable: a. Is public. b. Is private. c. Has package access. d. Is static. c. Has package access. Java programmers do not focus on: a. Crafting new classes and reusing existing classes. b. Understanding class library implementations c. Carefully testing classes they design. d. Carefully documenting classes they design. b. Understanding class library implementations Information hiding and well-defined interfaces free Java programmers from needing to understand existing class library implementations. Which of the following does not contribute to improved software reusability? a. Quickly creating new class libraries without testing them thoroughly. b. Licensing schemes and protection mechanisms. c. Descriptions of classes that allow programmers to determine whether a class fits their needs. d. Cataloging schemes and browsing mechanisms. a. Quickly creating new class libraries without testing them thoroughly. Abstract Data Types: a. Elevate the importance of data. b. Are only approximation or models of real-world concepts and behaviors. c. Capture tow notions, data representation and operations. d. All of the above. d. All of the above. The term information hiding refers to: a. public methods. b. Hiding implementation details from clients of a class. c. Accessing static class members.  d. The process of releasing an object for garbage collection. b. Hiding implementation details from clients of a class. Information is passed to a method in: a. the method name. b. that method's return. c. the called method. d. the arguments to the method. d. the arguments to the method. Counter-controlled repetition requires; a. A control variable and initial value. b. A control variable increment (or decrement). c. A condition that tests for the final value of the control variable. d. All of the above. d. All of the above. The control variable of a counter-controlled loop should be declared as: a. int. b. float. c. double. d. Any of the above. a. int. Consider the following two Java code segments: Segment 1 int i = 0; while ( i < 20 ) {            i++;            System.out.println( i );        } Segment 2 for ( int i = 0; i <= 20; i++ ) {             System.out.println( i );            }  Which of the following statements are true? a. The output from these segments is not the same. b. The scope of the control variable i is different for the two segments. c. Both (a) and (b) are true. d. Neither (a) nor (b) is true. c. Both (a) and (b) are true. Consider the classes below: public class TestA {        public static void main( String args[] )                  {               int x = 2, y = 20, counter = 0;     for ( int j = y % x; j < 100; j += ( y / x ) )         { counter++;}    } } public class TestB { public static void main(String args[]) {        int counter = 0;        for ( int j = 10; j > 0; --j ) {                ++counter;       }}  } Which of the following statements is true? a. The value of counter will be the different at the end of each for loop for each class. b. The value of j will be the same for each loop for all iterations c. Both (a) and (b) are true. d. Neither (a) nor (b) is true. d. Neither (a) nor (b) is true. Which of the following for-loop control headers results in equivalent numbers of iterations: A.  for ( int q = 1; q <= 100; q++ ) B.  for ( int q = 100; q >= 0; q-- ) C.  for ( int q = 99; q > 0; q -= 9 ) D.  for ( int q = 990; q > 0; q -= 90 ) a. A and B. b. C and D. c. A and B have equivalent iterations and C and D have equivalent iterations. d. None of the loops have equivalent iterations. b. C and D. Which of the following will count down from 10 to 1 correctly? a. for ( int j = 10; j <= 1; j++ ) b. for ( int j = 1; j <= 10; j++ ) c. for ( int j = 10; j > 1; j-- ) d. for ( int j = 10; j >= 1; j-- ) d. for ( int j = 10; j >= 1; j-- ) Which of the following statements about a do...while repetition statement is true? a. The body of a do...while loop is executed only if the terminating condition is true. b. The body of a do...while loop is executed only once. c. The body of a do...while loop is always executed at least once. d. None of the above c. The body of a do...while loop is always executed at least once. Which of the following will not help prevent infinite loops? a. Include braces around the statements in a do...while statement. b. Ensure that the header of a for or while statement is not followed by a semicolon. c. If the loop is counter-controlled, the body of the loop should increment or decrement the counter as needed. d. If the loop is sentinel-controlled, ensure that the sentinel value is input eventually. a. Include braces around the statements in a do...while statement. For the two code segments below: Segment A int q = 5; switch( q ) {          case 1: System.out.println( 1 );          case 2: System.out.println( 2 );          case 3: System.out.println( 3 );          case 4: System.out.println( 4 );          case 5: System.out.println( 5 );       default: System.out.println( "default" );   }  Segment B q = 4; switch( q ) {          case 1: System.out.println( 1 );          case 2: System.out.println( 2 );          case 3: System.out.println( 3 );          case 4: System.out.println( 4 );          case 5: System.out.println( 5 );       default: System.out.println( "default" );   }  Which of the following statements is true? b. The output for Segment A is:        default c. The output for Segment B is:         4 d. The output for Segment B is:         45default e. The output for Segment A is:              5              default e. The output for Segment A is:                      5                        default For the code segment below, switch( q ) {      case 1: System.out.println( "apple" );   break;      case 2: System.out.println( "orange" );   break;      case 3: System.out.println( "banana" );   break;      case 4: System.out.println( "pear" );      case 5: System.out.println( "grapes" );   default: System.out.println( "kiwi" ); }  Which of the following values for q will result in kiwi being output? a. 2. b. 4 and anything greater than 4. c. 1. d. 3. b. 4 and anything greater than 4. Which of the following statements about break and continue statements is true? a. The continue statement is used to exit a repetition structure early and continue execution after the loop. b. The continue statement is used to continue after a switch statement. c. The break statement, when executed in a while, for or do...while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. d. The continue statement, when executed in a while, for or do...while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. d. The continue statement, when executed in a while, for or do...while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. To exit out of a loop completely, and resume the flow of control at the next line in the method, use _______. a. A continue statement. b. A break statement. c. A return statement. d. Any of the above. b. A break statement. Which of the following statements is not true? A. A break statement can only break out of an immediately enclosing while, for, do...while or switch statement. B. Labeled break statements break out of any number of enclosing repetition structures. C. A continue statement proceeds with the next iteration of the immediately enclosing while, for, do...while statement. D. Labeled continue statements break out of any number of enclosing repetition structures, and continue execution with next iteration of the labeled repetition structure. a. A and C. b. B and D. c. None of the above are true. d. All of the above are true. d. All of the above are true. Labeled break statements cannot be used to break out of which of the following? a. A while statement. b. A method. c. A for loop. d. A switch statement. b. A method. Consider the code segment below.      if ( gender == 1 )         if ( age >= 65 )          ++seniorFemales; This segment is equivalent to which of the following? a. if ( gender == 1 || age >= 65)                  ++seniorFemales; b. if ( gender == 1 && age >= 65 )            ++seniorFemales; c. if ( gender == 1 AND age >= 65 )            ++seniorFemales; d. if ( gender == 1 OR age >= 65 )            ++seniorFemales; b. if ( gender == 1 && age >= 65 )            ++seniorFemales; Which case of the following would warrant using the boolean logical inclusive OR (|) rather than the conditional OR (||)? a. Testing if two conditions are both true. b. Testing if at least one of two conditions is true. c. Testing if at least one of two conditions is true when the right operand has a required side effect. d. Testing if at least one of two conditions is true when the left operand has a required side effect. c. Testing if at least one of two conditions is true when the right operand has a required side effect. Which statement below is not true? a. Structured programming produces programs are easier to test. b. Structured programming requires four forms of control. c. Structured programming produces programs that are easier to modify d. Structured programming promotes simplicity. b. Structured programming requires four forms of control. (Only three forms are necessary: sequence, selection, repetition) Which of the following is NOT a way that repetition is implemented in Java programs? a. while structures. b. do...while structures. c. for structures. d. if structures. d. if structures. Which of the following statements is not true? a. A subclass is generally larger than its superclass. b. A superclass object is a subclass object. c. The class following the extends keyword in a class declaration is the direct superclass of the class being declared. d. Java uses interfaces to provide the benefits of multiple inheritance. b. A superclass object is a subclass object. Which term applies to the largest class in a class hierarchy? a. Superclass. b. Subclass. c. Base class. d. Parent class. a. Superclass. Focusing on the commonalities among objects in a system rather than specifics is known as; a. Encapsulation. b. Abstraction. c. Inheritance. d. Simplification. b. Abstraction. Inheritance is also known as the; a. “knows-a” relationship. b. “has-a” relationship. c. “uses-a” relationship. d. “is-a” relationship. d. “is-a” relationship. Which of the following is not a superclass/subclass relationship? a. Ford/Taurus. b. University/Brown University. c. Sailboat/Tugboat. d. Country/USA. c. Sailboat/Tugboat. A Sailboat is not a superclass for Tugboats. Both sailboat and tugboats would be subclasses of Boat. An advantage of inheritance is that: a. All methods can be inherited. b. All instance variables can be uniformly accessed by subclasses and superclasses. c. Objects of a subclass can be treated like objects of their superclass. d. None of the above. c. Objects of a subclass can be treated like objects of their superclass. Note: constructors cannot be inherited, and instance variables that are private in a superclass cannot be directly accessed by a subclass. Which of the following keywords allows a subclass to access a superclass method even when the subclass has overridden the superclass method? a. protected. b. this. c. public. d. super. d. super. Using the protected keyword gives a member: a. public access. b. package access. c. private access. d. block scope. b. package access. Superclass methods with this level of access cannot be called from subclasses; a. private. b. public. c. protected. d. package. a. private. Overriding a method differs from overloading a method because; a. For an overloaded constructor, the superclass constructor will always be called first. b. For an overridden constructor, the superclass constructor will always be called first. c. Overloaded methods have the same signature. d. Overridden methods have the same signature. d. Overridden methods have the same signature. Consider the classes below, declared in the same file:       class A {                     int a;                     public A() {                         a = 7;                       }                   }       class B extends A {                     int b;                     public B() {                         b = 8;                                   }                              } Which of the statements below is not true? a. Both variables a and b are instance variables. b. After the constructor for class B is executed, the variable a will have the value 7. c. After the constructor for class B is executed, the variable b will have the value 8. d. A reference to class A can be treated as a reference to class B. d. A reference to class A can be treated as a reference to class B.  The converse is true because class A is the superclass. Note that variables a and b both have package access. Accessing a superclass method through a subclass reference is; a. Polymorphism. b. Inheritance. c. A syntax error. d. Straightforward. c. A syntax error. Private fields of a superclass can be accessed in a subclass; a. by calling private methods declared in the superclass. b. by calling public or protected methods declared in the superclass. c. directly. d. All of the above. b. by calling public or protected methods declared in the superclass. Which statement below is not true? a. Superclass finalizers should always be called as the last statement of a subclass finalizer. b. Superclass constructors should always be called as the first statement of a subclass constructor. c. Finalizers and constructors should always be declared protected so subclasses have access to the method. d. All are not true. c. Finalizers and constructors should always be declared protected so subclasses have access to the method. Constructors should be declared public so classes that use their classes can instantiate them. Finalizers are used to: a. Clean up an object of a class before it is garbage collected. b. Draw the applet or JFrame used by an application. c. Initialize variables. d. Ensure than all variables are assigned valid values. a. Clean up an object of a class before it is garbage collected. Which of the following sequences is in the correct order? a. Subclass constructor, superclass constructor, subclass finalizer, superclass finalizer. b. Superclass constructor, subclass constructor, superclass finalizer, subclass finalizer. c. Subclass constructor, superclass constructor, superclass finalizer, subclass finalizer. d. Superclass constructor, subclass constructor, subclass finalizer, superclass finalizer. d. Superclass constructor, subclass constructor, subclass finalizer, superclass finalizer. Which of the following statements are true? A. We can use inheritance to customize existing software. B. A superclass specifies commonality. C. A superclass can be modified without modifying subclasses D. A subclass can be modified without modifying its superclass. a. All of the above. b. None of the above. c. A, B and C. d. A, B and D. a. All of the above. Which of the following is an example of a functionality that should not be “factored out” to a superclass? a. Both ducks and geese are birds that know how to start flying from the water. b. All vehicles know how to start and stop. c. All animals lay eggs, except for mammals. d. All paints have a color. c. All animals lay eggs, except for mammals. Polymorphism enables the programmer to; a. program in the general. b. program in the specific. c. absorb attributes and behavior from previous classes. d. hide information from the user. a. program in the general. Classes declared completely inside other classes are called; a. subclasses. b. nested classes. c. superclasses. d. abstract classes. b. nested classes. Which statement best describes the relationship between superclass and subclass types? a. A subclass reference cannot be assigned to a superclass variable and a superclass reference cannot be assigned to a subclass variable. b. A subclass reference can be assigned to a superclass variable and a superclass reference can be assigned to a subclass variable. c. A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable. d. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. d. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. For which of the following would polymorphism not provide a clean solution? a. A billing program where there is a variety of clients who are billed with different fee structures. b. A maintenance log program where a variety of machine data is collected and maintenance schedules are produced for each machine based on the data collected. c. A program to compute savings account interest. d. An IRS program that maintains information on a variety of taxpayers and determines who to audit based on criteria for classes of taxpayers c. A program to compute savings account interest. Since there is only one kind of calculation, there is no need for polymorphism. Polymorphism allows for specifics to be dealt with during; a. execution time. b. compile time. c. programming. d. debugging. a. execution time. A(n) _______ class cannot be instantiated. a. final. b. concrete. c. abstract. d. static. c. abstract. Non-abstract classes are called; a. real classes. b. instance classes. c. instantiable classes. d. concrete classes. d. concrete classes. Declaring a non-abstract class with an abstract method is; a. allowable if the class is static. b. a syntax error. c. a logic error. d. none of the above. b. a syntax error. If the superclass contains only abstract method declarations, the superclass is used for: a. Implementation inheritance. b. Interface inheritance. c. Both a and b. d. Neither a nor b. b. Interface inheritance. Which of the following statements about abstract superclasses is true? a. abstract superclasses may contain data. b. abstract superclasses may not contain implementations of methods. c. abstract superclasses must declare all methods as abstract. d. abstract superclasses must declare all data members not given values as abstract. a. abstract superclasses may contain data. Classes and methods are declared final for all but the following reasons: a. final methods allow inlining the code. b. final methods and classes prevent further inheritance. c. final methods are static. d. final methods can improve performance. c. final methods are static. All of the following methods are implicitly final except; a. a method in an abstract class. b. a private method. c. a method declared in a final class. d. a static method. a. a method in an abstract class. Declaring a method final means; a. it will prepare the object for garbage collection. b. it cannot be accessed from outside its class. c. it cannot be overloaded. d. it cannot be overridden. d. it cannot be overridden. Consider the abstract superclass below:      public abstract class Foo {                              private int a;                              public int b;               public Foo( int aVal, int bVal )                             {                                  a = aVal;                                  b = bVal;                              }            public abstract int calculate();       } Any concrete subclass that extends class Foo; a. Must implement a method called calculate(). b. Will not be able to access the instance variable a. c. Will not be able to instantiate an object of class Foo. d. All of the above. d. All of the above. Consider the superclass below:       public class Foo {                      private int a;                      public int b;             public Foo( int aVal, int bVal )                                {                                 a = aVal;                                 b = bVal;                                  }            public int calculate()                   {                     return a + b;                   }           } A subclass that extends class Foo; a. Must override the method calculate(). b. Will not be able to access the instance variable a. c. Will not be able to instantiate an object of class Foo. d. All of the above. b. Will not be able to access the instance variable a. Which of the following does not complete the sentence correctly? An interface ____________ . a. Forces classes that implement it to declare all the interface methods. b. Is used in place of an abstract class when there is no default implementation to inherit. c. Is declared in a file by itself saved to the same name as the interface and the .java extension. d. Can be instantiated. d. Can be instantiated. To indicate that a reference always refers to the same object, use the keyword ________. a. abstract. b. final. c. static.  d. interface. b. final. An interface may contain; a. private static data and public abstract methods. b. only public abstract methods. c. public static final data and public abstract methods. d. private static data and public final methods. c. public static final data and public abstract methods. A class that implements an interface but does not declare all of the interface’s methods must be declared; a. public b. interface c. abstract d. final c. abstract Which of the following answers does not complete the sentence correctly? An inner class ____________ . a. Is frequently used for GUI event handling. b. May be anonymous. c. Does not need a handle to its outer class for methods and variables. d. Can access method variables from the method in which it was declared. d. Can access method variables from the method in which it was declared.  The inner class can only access final variables from the method. Consider the code segment below:   public class TestClassA {           private int var1;           public int var2;           private TestClassB tcB;           public TestClassA()             {                 var1 = 9;                 var2 = 11;                 tcB = new TestClassB();              }            public String toString()              {                  return "testclassA: " + var1 + " " + var2 + " " + tcB;               }        public static void main( String args[] )              {              TestClassA ai = new TestClassA();              System.out.println( ai );              }          private class TestClassB {                private int var3;                public int var4;          public TestClassB ()             {                var3 = var1 + var2;                var4 = var2 - var1;              }          public String toString()             {                 return "testclassb: " + var3 + " " + var4;             }      } } The output from this segment will be; a. testclassA: 9 11 testclassb: 20 2. b. None, accessing var1 in TestClassB will cause a syntax error. c. None, accessing var2 in TestClassB will cause a syntax error. d. testclassb: 20 2 testclassA: 9 11. a. testclassA: 9 11 testclassb: 20 2. Which of the following statements is true? a. All nested classes can be declared public, protected, package access or private. b. Each nested class is associated with the instantiation of one outer class and can only be accessed once instantiated. c. Each nested class will have its own .class file. d. None of these statements are true. c. Each nested class will have its own .class file. An inner class; a. is the same as a nested class. b. is defined in its own file. c. is non-static. d. is a top-level class. c. is non-static. Type wrapper classes; a. Enable you to manipulate primitives as objects. b. Enable you to manipulate primitives polymorphically. c. Exist for all primitive types. d. All of the above. d. All of the above. Which of the following is not a type-wrapper class? a. String. b. Short. c. Boolean. d. Character. a. String. The numeric type-wrapper classes extend which class? a. Object. b. Number. c. String. d. Byte. b. Number. In the Java coordinate system, the point (0,0) is; a. The lower-right corner of the screen. b. The upper-right corner of the screen. c. The lower-left corner of the screen. d. The upper-left corner of the screen. d. The upper-left corner of the screen. Which of the following statements about the Graphics object is true? A. The Graphics object is an argument to the applet's update method. B. The Graphics object is instantiated by the user. C. The Graphics object is the argument to the applet's paint method. D. The Graphics class is abstract. E. The Graphics object manages a graphics context. a. A, C, E. b. A, C, D, E. c. A, B, D, E. d. All are true. b. A, C, D, E. The Component method repaint causes; a. Component method update to be called only. b. Component method paint to be called only. c. Component method update to be called followed by calling Component method paint. d. Component method paint to be called followed by calling Component method update. c. Component method update to be called followed by calling Component method paint. Which of the following are valid Java statements, or groups of statements? A. Color c = new Color( 0, 255, 0 ); B. Color c = new Color( 0.0f, 1.0f, 0.0f ); C. Color c = new Color( 0.0d, 1.0d, 0.0d ); D. Color c = new Color( 0, 255, 0 ); E. setGreen( c.getGreen() – 2 ); a. All of the above. b. A, B, C. c. A, B, D. d. A, B. d. A, B. The JColorChooser dialog allows colors to be chosen by all but which of the following? a. Swatches. b. Hue, saturation, brightness. c. Gradient, cycle, brightness. d. Red, Green, Blue. c. Gradient, cycle, brightness. Which of the following are valid Font constructors? A. Font f = new Font(); B. Font f = new Font( "Serif", Font.Bold + Font.Italic, 19 ); C. Font f = new Font( Font.Bold, 20, "SansSerif" );  D. Font f = new Font( 20, Font.Bold, "Monospaced" ); a. A and B. b. B and C. c. B. d. D. c. B. Which of the following is correct for font metrics? a. height = descent + ascent + leading. b. The amount the character dips below the baseline is the ascent. c. The amount the character can be above the baseline is the leading. d. The amount the character rises above the baseline is the descent. a. height = descent + ascent + leading. The Java statement: g.fillOval( 290,100,90,55 ); a. Draws a filled oval with its center at coordinates x=290, y=100, with height=90 and width=55. b. Draws a filled oval with its left most point at coordinates x=290, y=100, with height=90 and width=55. c. Draws a filled oval bounded by a rectangle with its upper left corner at coordinates x=290, y=100, with height=55 and width=90. d. Draws a filled oval bounded by a rectangle with its upper left corner at coordinates x=290, y=100, with height 90=and width=55. c. Draws a filled oval bounded by a rectangle with its upper left corner at coordinates x=290, y=100, with height=55 and width=90. The Java statement; g.draw3DRect( 290,100,90,55,true ); a. draws a rectangle that is raised (the top and left edges of the rectangle are slightly darker than the rectangle). b. draws a rectangle that is lowered (the bottom and right edges of the rectangle are slightly darker than the rectangle). c. draws a rectangle that is raised (the bottom and right edges of the rectangle are slightly darker than the rectangle). d. draws a rectangle that is lowered (the top and left edges of the rectangle are slightly darker than the rectangle). c. draws a rectangle that is raised (the bottom and right edges of the rectangle are slightly darker than the rectangle). Which of the following statements about arcs is not true? a. An arc is drawn as a part of an oval. b. Arcs sweep from a starting angle the number of degrees specified by their arc angle. c. Arcs that sweep clockwise are measured in positive degrees. d. None of the above statements are false. c. Arcs that sweep clockwise are measured in positive degrees. Which of the following statement draws an arc that sweeps from the top of an oval to the left-most edge? The oval is twice as wide as high. a. g.drawArc( 200, 100, 100, 50, 90, 90 ); b. g.drawArc( 100, 200, 50, 100, 90, 180 ); c. g.drawArc( 100, 200, 50, 100, 180. 90 ); d. g.drawArc( 200, 100, 100, 50, 180, 90 ); a. g.drawArc( 200, 100, 100, 50, 90, 90 ); Consider the code segment below: int xValues[] = { 100, 150, 200, 100 }; int yValues[] = { 30, 130, 30, 30 }; g.drawPolyline( xValues, yValues, 4 ); This code segment will draw; a. A triangle with a corner at its upper most position and an edge at its lowest position. b. A triangle with an edge at its upper most position and a corner at its lowest position. c. A V with its corner at the top. d. A V with its corner at the bottom. b. A triangle with an edge at its upper most position and a corner at its lowest position. Consider the Java code segment below:        Polygon poly2 = new Polygon();        poly2.addPoint( 100, 30 );        poly2.addPoint( 100, 130 ); Which of the following will create a polygon that is a square? a. poly2.addPoint( 200, 30 );        poly2.addPoint( 200, 130 ); b. poly2.addPoint( 200, 130 );        poly2.addPoint( 200, 30 ); c. poly2.addPoint( 130, 30 );        poly2.addPoint( 130, 130 ); d. poly2.addPoint( 130, 130 );        poly2.addPoint( 130, 30 ); b. poly2.addPoint( 200, 130 );                      poly2.addPoint( 200, 30 ); Which of the following statements about the Java2D API is not true? a. A Graphics2D object is instantiated to draw Java2D figures. b. Class Graphics2D is a subclass of class Graphics. c. To access Graphics2D capabilities, downcast the Graphics reference passed to paint to a Graphics2D reference. d. All of the above are true. d. All of the above are true. The Graphics2D method(s) that determine(s) the color and texture for the shape to display is/are; a. setStroke(); b. setPaint(); c. setTexture() and setColor(); d. setTexturePaint(); b. setPaint(); Which of the following statements is not true? a. A BufferedImage object uses the image stored in its associated TexturePaint object as the fill texture for a filled-in shape. b. Class BufferedImage can be used to produce images in color and gray scale. c. Class GradientPaint draws a shape in a gradually changing color. d. All of the above are true. a. A BufferedImage object uses the image stored in its associated TexturePaint object as the fill texture for a filled-in shape. __________________________ is a form of software reusability in which new classes acquire the members of existing classes and embellish those classes with new capabilities. inheritance True/False  A has-a relationship is implemented via inheritance. False.   A "has a" relationship is implemented via composition. In a(n) _______ relationship, a class object has references to objects of other classes as members. has-a Which of the following is the superclass constructor call syntax? a) keyword super followed by a dot(.) b) keyword super followed by a set of parentheses containing the superclass constructor arguments c) keyword super followed by a dot(.) and the superclass constructor name d) None of the above b) keyword super followed by a set of parentheses containing the superclass constructor arguments A superclass's ____________ and ___________ members can be accessed in the superclass declaration and in subclass declarations. public and protected Inheritance is sometimes referred to as ___________________. specialization Which statement is true when a superclass has protected instance variables? a) A subclass object can assign an invalid value to the superclass's instance variables, thus leaving an object in an inconsistent state. b) Subclass methods are more likely to be written so that they depend on the superclass's data implementation.  c) We may need to modify all the subclasses of the superclass if the superclass implementation changes. d) ALL OF THE ABOVE d) ALL OF THE ABOVE are true a) A subclass object can assign an invalid value to the superclass's instance variables, thus leaving an object in an inconsistent state. b) Subclass methods are more likely to be written so that they depend on the superclass's data implementation.  c) We may need to modify all the subclasses of the superclass if the superclass implementation changes. True/False  Superclass constructors are not inherited by subclasses. True A subclass explicitly inherits from this kind of superclass; direct superclass This access modifier offers an intermediate level of access. Variables declared with this modifier in a superclass can be accessed by members of the superclass, by members of its subclasses, and by members of other classes in the same package; protected In a(n) ______ relationship, an object of a subclass can also be treated as an object of its superclass. is-a Fields labeled private in a superclass can be accessed in a subclass by; by calling public or protected methods declared in the superclass. Superclass methods with this level of access cannot be called from subclasses; private Every class in Java, except ________, extends an existing class. a) Integer b) Object c) String d) Class b) Object Subclass constructors can call superclass constructors via the keyword _________. super True/False   A Car class has a has-a relationship with the Vehicle class. False Overriding a method differs from overloading a method because: Overridden methods have the same signature. Choose the answer(s) that lists the complete set of statements that are true: a) A subclass is more specific than its superclass. c) A subclass can access the protected members of its superclass. d) A superclass method can be overridden in a subclass. e) The first task of any subclass constructor is to call its direct superclass's constructor. a) A subclass is more specific than its superclass. c) A subclass can access the protected members of its superclass. d) A superclass method can be overridden in a subclass. e) The first task of any subclass constructor is to call its direct superclass's constructor. Which of the following is the superclass constructor call syntax? a) keyword super followed by a dot(.) b) keyword super followed by a set of parentheses containing the superclass constructor arguments c) keyword super followed by a dot(.) and the superclass constructor name d) None of the above b) keyword super followed by a set of parentheses containing the superclass constructor arguments Inheritance is also known as the; "is-a" relationship. Composition is also known as the; "has-a" relationship. Private fields of a superclass can be accessed in a subclass by; by calling public or protected methods declared in the superclass. In single inheritance, a class exists in a(n) _______________ relationship with its subclasses. hierarchical Which of the keyword allows a subclass to access a superclass method even when the subclass has overridden the superclass method? super Which of the following statements is (are) true? a) We can use inheritance to customize existing software. b) A superclass specifies commonality. c) A superclass can be modified without modifying subclasses d) A subclass can be modified without modifying its superclass. e) All of the above e) All of the above True/False   When a subclass redefines a superclass method by using the same signature, the subclass is said to overload that superclass method. False Which of the following statements is false? a) A subclass is generally larger than it's superclass b) A superclass object is a subclass object c) The class following the extends keyword in a class declaration is the direct superclass of the class being declared d) java uses interfaces to provide the benefits of multiple inheritance b) A superclass object is a subclass object An advantage of inheritance is that: Objects of a subclass can be treated like objects of their superclass. Using the protected keyword gives a member: package access Every class in Java, except ________, extends an existing class. object To avoid duplicating code, use ________, rather than ________. inheritance, the "copy-and-past" approach. Consider the classes below, declared in the same file:          class A {int a;public A() {a = 7;}}       class B extends A {int b;public B() {b = 8;} } Which of the statements below is false? a) Both variables a and b are instance variables. b) After the constructor for class B executes, the variable a will have the value 7. c) After the constructor for class B executes, the variable b will have the value 8. d) A reference of type A can be treated as a reference of type B. d) A reference of type A can be treated as a reference of type B. Which superclass members are inherited by all subclasses of that superclass? protected instance variables and methods. Failure to prefix the superclass method name with the keyword super and a dot (.) separator when referencing the superclass's method causes ________. infinite recursion When a subclass constructor calls its superclass constructor, what happens if the superclass's constructor does not assign a value to an instance variable? a) A syntax error occurs b) A compile-time error occurs c) A run-time errors occurs d) the program compiles and runs because the instance variables are initialized to their default values. d) the program compiles and runs because the instance variables are initialized to their default values. Which of the following is an example of a functionality that should not be "factored out" to a superclass? a) Both ducks and geese are birds that know how to start flying from the water. b) All vehicles know how to start and stop. c) All paints have a color. d) All animals lay eggs, except for mammals. d) All animals lay eggs, except for mammals. The default implementation of method clone of Object performs a ________. a) empty copy b) deep copy c) full copy d) shallow copy d) shallow copy The default equals implementation determines: a) whether two references refer to the same object in memory. b) whether two references have the same type. c) whether two objects have the same instance variables. d) whether two objects have the same instance variable values. a) whether two references refer to the same object in memory. Class ________ represents an image that can be displayed on a JLabel. ImageIcon Which method changes the text the label displays? setText Polymorphism enables you to: program in the general If the superclass contains only abstract method declarations, the superclass is used for: interface inheritance Answer by choosing the correct set of true statements: a) Objects cannot be created from an abstract class. b) The purpose of an abstract class is to provide an appropriate superclass from which other classes can inherit and share the same design. c) You make a class abstract by declaring it with keyword abstract. d) Abstract classes are used as superclasses in inheritance hierarchies. e) All statements are true. e) All statements are true. Which of the following does not complete the sentence correctly? An interface; can be instantiated. Classes and methods are declared final for all but the following reasons: final methods are static. Classes from which objects can be instantiated are called __________ classes. concrete Assigning a subclass reference to a superclass variable is safe: a) because the subclass object has an object of its superclass. b) because the subclass object is an object of its superclass. c) only when the superclass is abstract. d) only when the superclass is concrete. b) because the subclass object is an object of its superclass. If a class contains at least one abstract method, it's a(n) ___________ class. abstract For which of the following would polymorphism not provide a clean solution? A program to compute a 5% savings account interest for a variety of clients. True/False  All methods in an abstract class must be declared as abstract methods. False Which of the following statements about abstract superclasses is true? abstract superclasses may contain data. An interface may contain: public static final data and public abstract methods. True/False  To use an interface, a concrete class must specify that it implements the interface and must declare each method in the interface with the signature specified in the interface declaration. True Which of the following statements about interfaces is false? An interface describes a set of methods that can be called on an object, providing a default implementation for the methods. Which statement best describes the relationship between superclass and subclass types? A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. Non-abstract classes are called: concrete classes Consider classes A, B and C, where A is an abstract superclass, B is a concrete class that inherits from A and C is a concrete class that inherits from B. Class A declares abstract method originalMethod, implemented in class B. Which of the following statements is true of class C? None of the above. True/False  Failure to implement a superclass's abstract methods in a subclass is a compilation error unless the subclass is also declared abstract. True Polymorphism allows for specifics to be dealt with during: execution Which keyword is used to specify that a class will define the methods of an interface? implements All of the following methods are implicitly final except: a method in an abstract class. This type of class cannot be a superclass. final It is a UML convention to denote the name of an abstract class in: italics A(n) ___________ class cannot be instantiated. abstract Which of the following could be used to declare abstract method method1 in abstract class Class1 (method1 returns an int and takes no arguments)? public abstract int method1(); When a superclass variable refers to a subclass object and a method is called on that object, the proper implementation is determined at execution time. What is the process of determining the correct method to call? a) execution time binding b) execution binding c) just in time binding d) late binding d) late binding Every object in Java knows its own class and can access this information through this method; getClass Declaring a method final means: it cannot be overridden. The UML distinguishes an interface from other classes by placing the word "interface" in ________________ above the interface name. guillemets Interfaces can have __________________  methods. any number of Which of the following is not possible? A class that inherits from two classes. A class that implements an interface but does not declare all of the interface's methods must be declared: abstract. Constants declared in an interface are implicitly; static True/False  In a class diagram, properties may be related to the instance variables of a class. True True/False  It is permissable to leave get and set methods for the instance variables of a class out of the class diagram. True Which of the following statements describe the type(s) of relationships that may be described by class diagrams? Only static relationships can be defined by class diagrams. Operations in a class diagram correspond to _____ in Java. methods The proper way to indicate that a class property may have no value entered into it is ____________. to use a lower bound of zero. Which of the following may be represented in a class diagram? Properties of a class. Operations or methods of a class. Constraints on relationships between classes. The UML syntax for operations includes which of the following: An argument list containing properties and types  A return type and property True/False  The features of a class can refer to both properties and operations. True Which of the following may be found in an attribute notation (select all that apply). A. Name C. Type   D. Visibility A. Name 33.333%  C. Type 33.333%  D. Visibility 33.333% True/False   Whether an operation is public or private is indicated by either + for private or - for public. False Something a business must track or that participates in the business may generally be called _________. a business object Which of the following should be visible to other objects? Operations Another way to talk about a superclass is: Parent The acronynm OMG (when discussing UML) stands for which of the following: Object management Group Polymorphism refers to the ability of _________ to take many "shapes". objects & operations True/False  A subclass may add attributes, operations, and relationships to those inherited from the superclass. True True/False  Polymorphism allows a subclass to override operations of a superclass, thus specializing the operation for the subclass. True The UML standard is owned by which of the following? OMG An object of a subclass automatically; inherits all the attributes and operations of its superclass. If two objects belong to the same class, which of the following statements about those objects is true? The procedure for carrying out a specific operation will be the same for both objects. A superclass defines a method called findArea. A subclass of that superclass also defines a method called findArea, but the subclass method uses a different formula. This is an example of ________. polymorphism A "method" is: an operation Two things that must be remembered about specific objects are (select two): Operations that my be performed by or on an object. Values of an object's attributes. The ways objects may be related are: Association, Aggregation, Composition. True/False  Attributes and operations defined at the class level will be shared by all objects of that class. True True/False  Once a subclass is formed, no further inheritance from that subclass is allowed. False True/False  A subclass can effect state changes in superclass private members only through public, protected methods provided in the superclass and inherited into the subclass. True True/False  Subclasses provide the functionality and features inherited by superclasses. False True/False  A superclass's constructors are inherited into its subclasses. False True/False  Subclass methods can normally refer to protected and private members of the superclass simply by using the member names. False True/False  Protected members are accessible only to methods of their class and to methods of their subclasses. False True/False  To call the superclass default (no-argument) constructor explicitly, use the statement: super(); True True/False  Assigning an object of a superclass to a subclass reference (without a cast) is a syntax error. True True/False  An explicit call to the superclass constructor must be provided as the first statement in the subclass constructor. False True/False  When a superclass method is overridden in a subclass, it is common to have the subclass version call the superclass version and do some additional work. True True/False  When creating subclasses, programmers must use discretion in choosing the proper superclass. Ideally, the superclass will not contain superfluous capabilities or information. True True/False  Method equals will accurately compare any two objects. False True/False  An object of class ImageIcon can be used to represent an image in a program. True True/False  Method setLabel specifies the text that should appear on a JLabel. False True/False  Unfortunately, polymorphic programs make it difficult to add new capabilities to a system. False True/False  Polymorphism enables objects of different classes that are related by a class hierarchy to be processed generically. True True/False  The major drawback to polymorphically designed programs is that they do not take into account the future addition or deletion of classes. False Polymorphically designed programs are extremely extensible and easily handle new classes that extend the same hierarchy of classes processed by the program. Review Section: 10.1 Introduction True/False  An abstract class declares a common interface for the various members of a class hierarchy. The abstract class contains methods that will be declared in the subclasses. All classes in the hierarchy can use this same set of methods through polymorphism. True True/False  Polymorphism is particularly effective for implementing layered software systems. True True/False  Casting superclass references to subclass references is known as downcasting. True True/False  If a subclass reference is assigned to a superclass variable, the variable must be cast back to the subclass before any subclass methods can be called with it. True Section: 10.3 Demonstrating Polymorphic Behavior True/False  Objects of abstract superclasses can be instantiated. False Only objects of concrete classes can be instantiated. Review Section: 10.4 Abstract Classes and Methods True/False  An abstract class cannot have instance data and non-abstract methods. False  An abstract class can have instance data and non-abstract methods. Review Section: 10.5 Case Study: A Payroll System Using Polymorphism True/False  Attempting to instantiate an object of an abstract class is a logic error. False True/False  A method that is declared final cannot be overridden in a subclass. True Section: 10.6 final Methods and Classes True/False  All methods in a final class must be explicitly declared final. False True/Final  If a class leaves one method in an interface undeclared, the class is implicitly declared by Java as an abstract class. False If a class leaves one method in an interface undeclared, the class becomes an abstract class and must be declared abstract in the first line of its class declaration. Review Section: 10.7 Case Study: Creating and Using Interfaces True/False  An interface is typically used in place of an abstract class when there is no default implementation to inherit. True Consider the examples below: A. a string. B. 'a string'. C. "a string". D. "1234". E. integer. Which could be the value of a Java variable of type String? a. A and B. b. B and E. c. B and C. d. C and D. d. C and D. An anonymous String: a. has no value. b. is a string literal. c. can be changed. d. none of the above. b. is a string literal. A String constructor cannot be passed variables of type: a. char arrays. b. int arrays. c. byte arrays. d. Strings. b. int arrays. String objects are immutable. This means they: a. Must be initialized. b. Cannot be deleted. c. Cannot be changed. d. None of the above c. Cannot be changed. The length of a string can be determined by: a. The String method length(). b. The String instance variable length. c. The String method strlen(). d. All of the above. a. The String method length(). How many String objects are instantiated by the following code segment (not including the literals)?   String s1, output;   s1 = "hello";     output += "nThe string reversed is: " ;     for ( int i = s1.length() - 1; i >= 0; i-- )      output += s1.charAt( i ) + " " ; a. 2. b. 1. c. 4. d. 5. a. 2. The statement s1.equalsIgnoreCase( s4 ) is equivalent to which of the following? a. s1.regionMatches( true, 0, s4, 0, s4.length() ); b. s1.regionMatches( 0, s4, 0, s4.length() ); c. s1.regionMatches( 0, s4, 0, s4.length ); d. s1.regionMatches( true, s4, 0, s4.length ); a. s1.regionMatches( true, 0, s4, 0, s4.length() ); The statement; s1.startsWith( "art" ) has the same result as which of the following? a. s1.regionMatches( 0, "art", 0, 3 ); b. s2 = s1.getChars( 0, 3 );               s2.equals( "art" ); c. s1.regionMatches( true, 0, "art", 0, 3 ); d. All of the above d. All of the above For   String c = "hello world"; The Java statements; int i = c.indexOf( 'o' ); int j = c.lastIndexOf( 'l' ); will result in: a. i = 4 and j = 8. b. i = 5 and j = 8. c. i = 4 and j = 9. d. i = 5 and j = 9. c. i = 4 and j = 9. For   String c = "Hello. She sells sea shells"; The Java statements; int i = c.indexOf( "ll" ); int j = c.lastIndexOf( "ll" ); will result in: a. i = 2 and j = 24. b. i = 3 and j = 24. c. i = 2 and j = 25. d. i = 3 and j = 23. a. i = 2 and j = 24. For   String c = "Now is the time for all"; The Java statements; String i = c.substring( 7 ); String j = c.substring( 4, 15 ); will result in: a. i = "he time for all" and j = "is the time". b. i = "the time for all" and j = "s the time". c. i = "the time for all" and j = "is the time ". d. i = "he time for all" and j = "s the time". c. i = "the time for all" and j = "is the time ". The String method substring returns: a. A char. b. A String. c. void. d. A char[]. b. A String. Consider the statements below: String a = "JAVA: "; String b = "How to "; String c = "Program"; Which of the statements below will create the String r1 = "JAVA: How to Program"? a. String r1 = c.concat( b.concat( a ) ); b. String r1 = a.concat( b.concat( c ) ); c. String r1 = b.concat( c.concat( a ) ); d. String r1 = c.concat( c.concat( b ) ); b. String r1 = a.concat( b.concat( c ) ); ConsidertheString below:          String r = "a toyota"; Which of the following will create the String r1 = "a TOYOTa"? a. r1 = r.replace( "toyot", TOYOT" ); b. r1 = r.replace( 't','T' );           r1 = r.replace( 'o','0' );           r1 = r.replace( 'y','Y' ); c. r1 = r.replace( 't','T' ).replace( 'o', '0'                        ).replace( 'y', 'Y' ); d. r1 = r.substring( 2, 4 ).toUpperCase(); c. r1 = r.replace( 't','T' ).replace( 'o', '0'                         ).replace( 'y', 'Y' ); Which of the following is not a method of class String? a. toUpperCase. b. trim. c. toCharacterArray. d. All of the above are methods of class String. c. toCharacterArray. Which of the following will create a String different from the other three? a. String r = "123456" b. int i = 123;     int j = 456;     String r = String.valueOf(j) +              String.valueOf(i); c. int i = 123;      int j = 456;     String r = String.valueOf(i) +              String.valueOf(j); d.int i = 123; int j = 456; String r = i + j; b. int i = 123;    int j = 456;    String r =           String.valueOf(j) + String.valueOf(i); StringBuffer objects can be used in place of String objects if: a. The string data is not constant. b. The string data size may grow. c. Performance is not critical. d. All of the above. d. All of the above. Given the following declarations: StringBuffer buf; StringBuffer buf2 = new StringBuffer(); String c = new String( "test" ); Which of the following is not a valid StringBuffer constructor? a. buf = new StringBuffer(); b. buf = new StringBuffer( buf2 ); c. buf = new StringBuffer( 32 ); d. buf = new StringBuffer( c ); b. buf = new StringBuffer( buf2 ); Given the following declaration: StringBuffer buf = new StringBuffer(); What is the capacity of buf? a. 0 b. 10 c. 16 d. 20 c. 16 Which of the following statements is true? a. The capacity of a StringBuffer is equal to its length. b. The capacity of a StringBuffer cannot exceed its length. c. The length of a StringBuffer cannot exceed its capacity. d. Both a and b are true. c. The length of a StringBuffer cannot exceed its capacity. Given the following declarations: StringBuffer buffer = new StringBuffer( “Testing Testing” ); buffer.setLength( 7 ); buffer.ensureCapacity( 5 ); Which of the following is true? a. buffer has capacity 5. b. buffer has capacity 31. c. buffer has content “Testin”. d. buffer has length 15. b. buffer has capacity 31. Consider the statement below: StringBuffer sb1 = new StringBuffer( "a toyota" ); Which of the following creates a String object with the value "toy"? a. String res = sb1.subString( 2, 5 ); b. char dest[];       sb1.getChars( 2, 4, dest, 0 );       String res = new String( dest ); c. char dest[] = new char[ sb1.length ];       dest = sb1.getChars( 2, 5 );       String res = new String( dest ); d. char dest[] = new char[ sb1.length() ];       dest = sb1.getChars( 0, 3 ); String res = new String( dest ); b. char dest[];                sb1.getChars( 2, 4, dest, 0 );           String res = new String( dest ); To find the character at a certain index position within a String, use the method: a. getChars, with the index as an argument. b. getCharAt, with the index as an argument. c. charAt, with the index as an argument. d. charAt, with the character you are searching for as an argument. c. charAt, with the index as an argument. Which of the following creates the string of the numbers from 1 to 1000 most efficiently? a. String s;      for ( int i = 1; i <= 1000; i++ )      s += i; b. StringBuffer sb = new StringBuffer( 10 );      for ( int i = 1; i <= 1000; i++ )      sb.append( i );      String s = new String( sb ); c. StringBuffer sb = new StringBuffer( 3000 );      for ( int i = 1; i <= 1000; i++ )      sb.append( i );      String s = new String( sb ); d. All are equivalently efficient. c. StringBuffer sb = new StringBuffer( 3000 );                 for ( int i = 1; i <= 1000; i++ )            sb.append( i );            String s = new String( sb ); Consider the statements below: StringBuffer sb = new StringBuffer( "a toyota" );      sb.insert( 2, "landrover" );      sb.delete( 11, 16 );      sb.insert( 11, " " ); The StringBuffer contents at the end of this segment will be: a. a landrovertoyota. b. a landrover a. c. a landrov a. d. a landrover toy a. b. a landrover a. Which of the following are static Character methods? a. Character.hashcode( char c ); b. Character.isDigit( char c ); c. Character.equals( char c ); d. All of the above. b. Character.isDigit( char c ); Which class is not a type-wrapper class? a. Character b. Int c. Double d. Byte b. Int Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1, delimArg ); For the String line1 to have 4 tokens, delimArg should be: a. String delimArg = "+="; b. String delimArg = "123" c. String delimArg = "c+"; d. String delimArg = " "; a. String delimArg = "+="; Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1 ); int count = tok.countTokens(); The value of count is: a. 8. b. 7. c. 13. d. 4. b. 7. Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1, "+=" ); String foo = tok.nextToken(); String bar = tok.nextToken(); The values of foo and bar are: a. foo is “c ”, bar is “ = ”. b. foo is “c”, bar is “ ”. c. foo is “ = ”,bar is “ + ”. d. foo is “c ”, bar is “ 1 ”. d. foo is “c ”, bar is “ 1 ”. Which of the following is not a word character? a. w b. 0 c. _ d. & d. & Which of the following statements is true? a. Ranges of characters can be represented by placing a ~ between two characters. b. [^Z] is the same as [A~Y]. c. Both “A*” and “A+” will match “A”, but only “A*” will match an empty string. d. All of above. c. Both “A*” and “A+” will match “A”, but only “A*” will match an empty string. Which of the Java strings represent the regular expression ,s*? a. “,s*”. b. “,s*”. c. “,s*”. d. “.s*”. b. “,s*”. Which of the following statements is true? a. Class Matcher provides methods find, lookingAt, replaceFirst and replaceAll. b. Method matches (from class String, Pattern or Matcher) will return true only if the entire search object matches the regular expression. c. Methods find and lookingAt (from class Matcher) will return true if a portion of the search object matches the regular expression. d. All of above. d. All of above. Which of the following is not a specific GUI component (control or widgit)? a. String. b. Label. c. Menu. d. List. a. String. Which of the following is not a benefit of using Swing GUI components? a. Most Swing components are heavyweight. b. Most Swing components are written completely in Java c. Swing components allow the user to specify a uniform look and feel across all platforms. d. Swing components allow the user to change the look and feel while the program is running. a. Most Swing components are heavyweight. Which pair of words does not complete the sentence below correctly? A _______ is a ________. a. Container/Component. b. JComponent/Container. c. Component/Object. d. Container/JPanel. d. Container/JPanel. Which of the following is not a valid constructor for a JLabel? a. JLabel( int, horizontalAlignment, Icon image ); b. JLabel( Icon image ); c. JLabel( String text, Icon image, int horizontalAlignment ); d. JLabel( String text, int horizontalAlignment ); a. JLabel( int, horizontalAlignment, Icon image ); Which of the following steps is not required to use a JLabel as a GUI component? a. Declare a reference to a JLabel. b. Add to the contentPane(). c. Instantiate the JLabel. d. Initialize the JLabel text. d. Initialize the JLabel text. Which of the following generate GUI events? A. Typing in a text field. B. Selecting an item from a menu. C. Calling an itemListener. D. Calling an adjustmentListener. a. A and B. b. B and C. c. C and D. d. A and D. a. A and B. Consider the abstract superclass below:             public abstract class Foo {                                                          private int a;                                                                     public int b;                         public Foo( int aVal, int bVal )                                                       {                                                        a = aVal;                                                        b = bVal;                             }                            public abstract int calculate();                  } Any concrete subclass that extends class Foo; a. Must implement a method called calculate(). b. Will not be able to access the instance variable a. c. Neither a nor b. d. Both a and b. d. Both a and b. Which of the following completes the sentence below correctly? A(n) _______ is a(n) __________. a.InputEvent/MouseEvent. b.ActionEvent/AdjustmentEvent. c.FocusEvent/WindowEvent. d.ContainerEvent/ComponentEvent. d.ContainerEvent/ComponentEvent. Which of the following is not necessary to use the event delegation model? a. An event listener must be registered. b. An event handler must be implemented. c. The appropriate interface must be implemented. d. The appropriate interface must be registered. d. The appropriate interface must be registered. Which of the following statements about JTextFields and JPasswordFields is not true? a. A JTextField is a JTextComponent. b. A JTextField is a JPasswordField. c. JPasswordField(String text,int columns)isavalidconstructor. d. JTextField(String text,int columns)isavalidconstructor. b. A JTextField is a JPasswordField. JTextField and JPasswordField events are handled using which interfaces? a. Both use the ActionListener interface. b. Both use the TextFieldListener interface. c. Both use the TextComponentListener interface. d. They use TextFieldListener and ActionListener interfaces respectively. a. Both use the ActionListener interface. Which of the following choices completes the sentence correctly? A ____ is a(n) _____ a. ToggleButton/JCheckBox. b. ToggleButton/JRadioButton. c. JButton/ToggleButton. d. JButton/AbstractButton. d. JButton/AbstractButton. The method setRolloverIcon is used to: a. Handle a mouse event. b. Change the button text. c. Change the button icon. d. All of the above. c. Change the button icon. Which of the following is stateless? a. JRadioButton. b. JToggleButton. c. JCheckBox. d. JButton. d. JButton. Which of the following does not generate an item event when pressed? a. JRadioButton. b. JToggleButton. c. JCheckBox. d. JButton. d. JButton. When a JComboBox is clicked on: a. An ItemEvent is generated. b. A scrollbar is always generated. c. An ActionEvent is generated. d. The JComboBox expands to a list. d. The JComboBox expands to a list. The setMaximumRowCount method is used for: a. Button. b. JComboBox. c. JRadioButton. d. JToggleButton. b. JComboBox. A JScrollPane is provided for which of the following: a. JToggleButton. b. JRadioButton. c. JList. d. None of the above. d. None of the above. Selecting a JList item creates: a. An ActionEvent. b. A ListItemEvent. c. A ListSelectionEvent. d. A ListActionEvent. c. A ListSelectionEvent. Consider the list below: January February March April May June July August September November December What type of JList selection mode would allow the user to select March, June, and July in one step. a. SINGLE_SELECTION.  b. SINGLE_INTERVAL_SELECTION. c. MULTIPLE_INTERVAL_SELECTION. d. All of the above. c. MULTIPLE_INTERVAL_SELECTION. Which of the following objects can not trap mouse events? a. JTextField. b. ButtonGroup. c. JButton. d. JComponent. b. ButtonGroup. Which of the following is a MouseMotionListener method? a. mousePressed. b. mouseExited. c. mouseDragged. d. mouseClicked. c. mouseDragged. Which of the following statements about adapters is false? a. An adapter class implements an interface. b. Programmers provide a default (empty) implementation of every method in the interface. c. Programmers override selected adapter methods. d. A ComponentAdaptor is a ComponentListener. b. Programmers provide a default (empty) implementation of every method in the interface. A one-button mouse can simulate pushing the middle button on a three-button mouse by: a. Holding the alt-key while clicking the mouse button. b. Holding the meta-key while clicking the mouse button. c. Holding the ctrl-key while clicking the mouse button. d. Holding the shift-key while clicking the mouse button. a. Holding the alt-key while clicking the mouse button. Which of the following is not a KeyListener method? a. keyPressed. b. keyRelease. c. keyClicked. d. keyTyped. c. keyClicked. The Shift key is a _________ key. a. Modifier. b. Action. c. Output. d. None of the above. a. Modifier. Which layout manager is the default for JFrame? a. FlowLayout.  b. BorderLayout. c. GridLayout. d. None of the above. b. BorderLayout. The layout manager that allows alignment to be controlled is: a. FlowLayout. b. BorderLayout. c. GridLayout. d. None of the above. a. FlowLayout. FlowLayout is: a. An abstract class. b. A way of organizing components vertically. c. The simplest layout manager. d. Left-aligned by default. c. The simplest layout manager. BorderLayout implements interface: a. ActionListener. b. FlowLayout. c. Layout. d. LayoutManager2. d. LayoutManager2. The BorderLayout layout manager: a. Divides an area into five regions: NORTH, SOUTH, EAST, WEST, and CENTER. b. Divides an area into five regions: UP, DOWN, LEFT, RIGHT, and MIDDLE. c. Orders components vertically. d. Orders components horizontally. a. Divides an area into five regions: NORTH, SOUTH, EAST, WEST, and CENTER. The class GridLayout constructs _________ to hold components. a. A horizontal grid with one row. b. A vertical grid with one column. c. A grid with m rows and n columns. d. A square grid with the same number of rows as columns. c. A grid with m rows and n columns. When components are added to a container with a GridLayout, the component: a. Fills the next spot in the row, continuing in the first position of the next row if the current row is full. b. Fills the next spot in a column, continuing in the first position of the next column if the column is full. c. Fills in row x, column y if x and y are two integers passed to the Container method add. d.Fills in a random empty position in the grid. a. Fills the next spot in the row, continuing in the first position of the next row if the current row is full. Which of the following statements about JPanels is not true? a. A JPanel is a JComponent. b. A JPanel is a Container. c. Mouse events can be trapped for a JPanel. d. A JPanel has a fixed size. d. A JPanel has a fixed size. ________________ is a form of software reusability in which new classes acquire the members of existing classes and embellish those classes with new capabilities. Inheritance A superclass's ________________ members can be accessed in the superclass declaration and in subclass declarations. public and protected In a _____________________ relationship, an object of a subclass can also be treated as an object of it's superclass. is-a or inheritance In a ____________________ relationship, a class object has references to objects of other classes as members. has-a or composition In single inheritance, a class exists in a ______________ relationship with its subclasses. hierarchical List five common examples of exceptions; 1. memory exhaustion 2. array index out of bounds 3. arithmetic overflow 4. division by zero 5. invalid method parameters Give several reasons why exception-handling techniques should not be used for conventional program control; a) Exception handling is designed to handle infrequently occurring situations that often result in program termination, not situations that arise all the time. b) Flow of control with conventional control structures is generally clearer and more efficient than with exceptions.   c) The additional exceptions can get in the way of genuine error-type exceptions. d) It becomes more difficult for you to keep track of the larger number of exception cases. Why are exceptions particularly appropriate for dealing withe errors produced by methods of classes in the Java API? It's unlikely that methods of classes in the Java API could perform error processing that would meet the unique needs of all users. What is a resource leak? A "resource leak" occurs when an executing program does not properly release a resource when it's no longer needed. If no exceptions are thrown in a try block, where does control proceed to when the try block completes execution? The catch blocks for that try statement are skipped, and the program resumes execution after the last catch block.  If there's a finally block, it's executed first; then the program resumes execution after the finally block. Give a key advantage of using catch(Exception exceptionName); The form catch(Exception exceptionName) catches any type of exception thrown in a try block.  An advantage is that known thrown exception can slip by without being caught.  You can then decide to handle the exception or possibly rethrow it. Should a conventional application catch error objects?  Explain. Errors are usually serious problems with the underlying Java system; most programs will not want to catch errors because they will not be able to recover from them. What happens if no catch handler matches the type of a thrown object? This causes the search for a match to continue in the next enclosing try statement.  If there's a finally block, it will be executed before the exception goes to the next enclosing try statement.  If there are no enclosing try statements for which there are matching catch blocks and the exceptions are declared (or unchecked), a stack trace is printed and the current thread terminates early.  If the exceptions are checked, but not caught or declared, compilation errors occurs. All of the following are true about classes except; a) Classes have attributes and behaviors b) A class's functions hide from the user the complex tasks they perform c) An object must be created from a class before it can be used d) The first class in any C++ program is main d) The first class in any C++ program is main Function headers contain all of the following except: a) Left brace b) Return type c) Name of function d) Parenthesis a) Left brace C++ functions other than main are executed: a) Never b) After main completes execution c) Before main executes d) When they are explicitly called by another function d) When they are explicitly called by another function An object creation expression contains: a) The name of the class b) Parenthesis c) The name of the object d) All of the above d) All of the above Polymorphism enables you to; a) program in the general b) program in the specific c) absorb attributes and behavior from previous classes d) hide information from the user a) program in the general Calling a member function of an object requires which item? a) The class name b) The dot separator c) Open and close braces d) None of the above b) The dot separator In the UML, the top compartment of the rectangle modeling a class contains: a) The class's name b) The class's attributes c) The class's behavior d) All of the above a) The class's name Which of the following is an example of a functionality that should not be "factored out" to a superclass? a) Both ducks and geese are birds that know how to start flying from the water b) All vehicle know how to start and stop c) All animals lay eggs, except for mammals d) All paints have a color c) All animals lay eggs, except for mammals What is the name of the values the method call passes to the method for the parameters? a) Object b) Values c) References d) Arguments d) Arguments Assuming that text is a variable of type string, what will be the contents of text after the statement cin >> text; is executed if the user types “Hello World!” and then presses Enter? a) H b) Hello c) Hello World! d) Hello World b) Hello Multiple parameters are separated by what symbol? a) The dot separator b) Commas c) Parenthesis d) Braces b) Commas Attributes of a class are also known as; a) local variable b) classes c) constructors d) data members d) data members Which of the following statements is (are) true? A) We can use inheritance to customize existing software B) A superclass specifies commonality C) A superclass can be modified without modifying subclasses D) A subclass can be modified without modifying its superclass a) A, B and C b) A, B and D c) All of the above d) None of the above c) All of the above An advantage of inheritance is that; a) All methods can be inherited b) All instance variables can be uniformly accessed by subclasses and superclasses c) Objects of a subclass can be treated like objects of their superclass d) None of the above c) Objects of a subclass can be treated like objects of their superclass What is the default initial value of a String? a) default b) "" c) "default" d) null d) null Textbook Page 82 What type of member functions allow a client of a class to assign values to private data members? a) set member functions b) assign member functions c) access member functions d) client member functions a) set member functions A default constructor has how many parameters? a) Variable b) 0 c) 2 d) 1 b) 0 A constructor can specify the return type; a) void b) A constructor cannot specify a return type c) string d) int b) A constructor cannot specify a return type The compiler will implicitly create a default constructor if: a) the class does not define any constructors b) the programmer specifically requests that a compiler do so c) the class already defines a default constructor d) the class does not contain any data members a) the class does not define any constructors Inheritance is also known as the; a) "knows-a" relationship b) "has-a" relationship c) "uses-a" relationship d) "is-a" relationship d) "is-a" relationship Which statement is false? a) An enum declaration is a comma-separated list of enum constants and may optionally include other components of traditional classes, such as constructors, fields and methods. b) Any attempt to create an object of an enum type with operator and new results in a compilation error. c) An enum constructor cannot be overloaded. d) An enum constructor can specify any number of parameters. c) An enum constructor cannot be overloaded. Textbook Page 331 - An enum constructor CAN be overloaded. A header file is typically given the filename extension; a) .hdr b) .cpp c) .h d) .header c) .h Assuming that GradeBook.h is found in the current directory and the iostream header file is found in the C++ Standard Library header file directory, which of the following preprocessor directives will fail to find its desired header file? a) #include. b) #include. c) #include "iostream". d) #include "GradeBook.h". b) #include. In the source-code file containing a class’s member function definitions, each member function definition must be tied to the class definition by preceding the member function name with the class name and ::, which is known as the: a) member definition linker b) binary scope resolution operator c) class implementation connector d) source code resolver b) binary scope resolution operator When compiling a class’s source code file (which does not contain a main function), the information in the class’s header file is used for all of the following, except; a) Ensuring that each member function knows about the class's data members and other member functions. b) Ensuring that the first line of each member function matches its prototype. c) Determining the correct amount of memory to allocate for each object of the class. d) All of the above are uses that the compiler has for the header file information. c) Determining the correct amount of memory to allocate for each object of the class. When a client code programmer uses a class whose implementation is in a separate file from its interface, that implementation code is merged with the client’s code during the; a) Linking phase b) Programming phase c) Compiling phase d) Executing phase a) Linking phase Composition is sometimes referred to as a(n) __________. a) is-a relationship b) has-a relationship c) many-in-one relationship d) one-to-many relationship b) has-a relationship When implementing a method, use the class's set and get methods to access the class's  _____________ data. a) public b) private c) protected d) All of the above b) private Non-abstract classes are called; a) real classes b) instance classes c) implementable classes d) concrete classes d) concrete classes Polymorphism allows for specifics to be dealt with during; a) execution b) compilation c) programming d) debugging a) execution To execute multiple statements when an if statement’s condition is true, enclose those statements in a pair of; a) Parenthesis, (). b) Square brackets, []. c) Angle brackets, <>. d) Braces,{}. d) Braces,{}. Assuming that the string object text contains the string “Hello!!!”, the expression text.substr( 2 , 5 ) would return a string object containing the string; a) "llo!!" b) "ello!" c) "ello" d) "llo!" d) "llo!" A solid line representing an association between two classes can be accompanied by any of the following details, except; a) An aggregation relationship with another association line b) A name and direction for the association c) A role name for one or both of the objects d) A number near the end of each one indication multiple values a) An aggregation relationship with another association line A composition or “has-a” relationship is represented in the UML by; a) Making the association line dashed b) Making the association line bolded c) Attaching a solid triangle to the association line d) Attaching a solid diamond to the association line d) Attaching a solid diamond to the association line A(n) __________ class cannot be instantiated. a) final b) concrete c) abstract d) polymorphic c) abstract Which statement best describes the relationship between superclass and subclass types? a) A subclass reference cannot be assigned to a superclass variable and a superclass reference cannot be assigned to a subclass variable. b) A subclass reference can be assigned to a superclass variable and a superclass reference can be assigned to a subclass variable. c) A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable.  d) A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. d) A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. __________________ is a form of software reusability in which new classes acquire the members of existing classes with new capabilities. Inheritance True/False;  A "has-a" relationship is implemented via inheritance. False Java was originally developed for; a) Operating systems development b) Intelligent consumer devices c) Personal computers d) Distributed computing b) Intelligent consumer devices Which of the following is not a valid Java identifier? a) my Value b) $_AAA1 c) width d) m_x a) my Value Java identifiers may not contain blanks (spaces). Which is the output of the following statement; System.out.print("Hello "); System.out.println("World"); a) Hello World b) HelloWorld c) Hello World d) World Hello a) Hello World Which of the following is a variable declaration statement? a) int total; b) import java.util.Scanner c) public static void main(String args[]) d) // first string entered by user a) int total; A class instance creation expression contains; a) Parentheses b) The new keyword c) The name of the class d) All of the above d) All of the above Which of the following should usually be private? a) Methods b) Constructors c) Variables (or fields) d) All of the above c) Variables (or fields) What is the default initial value of a String instance variable? a) "" b) "default" c) default d) null d) null Textbook page 82 Which of the following is not a control structure? a) Sequence structure b) Selection structure c) Repetition structure d) Declaration structure d) Declaration structure What is output by the following Java code segment? int temp; temp = 200;    if ( temp > 90 )       System.out.println( "This porridge is too                          hot." );    if ( temp < 70 )       System.out.println( "This porridge is too                        cold." );    if ( temp == 80 )       System.out.println( "This porridge is just                        right!" ); a) This porridge is too hot. b) This porridge is too cold. c) This porridge is just right! d) None of the above a) This porridge is too hot. How many times is the body of the loop below executed?        int counter;        counter = 1;         while ( counter > 20 ) { // body of loop counter = counter + 1; } // end while a. 19. b. 20. c. 21. d. 0. d. 0. Nothing increments the counter so it is always = 1 and never > 20. Which statement is true? a. Dividing two integers results in integer division. b. With integer division, any fractional part of the calculation is lost. c. With integer division, any fractional part of the calculation is truncated. d. All of the above. d. All of the above. Suppose method1 is declared as;      void method1(int a, float b) Which of the following methods correctly overloads method1? a) void method2(int a, float b) b) void method2(float a, int b) c) void method1(float a, int b) d) void method1(int b, float a) c) void method1(float a, int b) What does the expression x %= 10 do? a. Adds 10 to the value of x, and stores the result in x. b. Divides x by 10 and stores the remainder in x. c. Divides x by 10 and stores the integer result in x. d. None of the above. b. Divides x by 10 and stores the remainder in x. Consider the classes below: public class TestA { public static void main( String args[] ) { int x = 2, y = 20, counter = 0; for ( int j = y % x; j < 100; j += ( y / x ) ) counter++; } // end main } // end class TestA public class TestB { public static void main(String args[]) { int counter = 0; for ( int j = 10; j > 0; --j ) ++counter; } // end main } // end class TestB Which of the following statements is true? a. The value of counter will be different at the end of each for loop for each class. b. The value of j will be the same for each loop for all iterations c. Both (a) and (b) are true. d. Neither (a) nor (b) is true. d. Neither (a) nor (b) is true. Which of the following statements about a do¡Kwhile repetition statement is true? a. The body of a do¡Kwhile loop is executed only if the terminating condition is true. b. The body of a do¡Kwhile loop is executed only once. c. The body of a do¡Kwhile loop is always executed at least once. d. None of the above c. The body of a do¡Kwhile loop is always executed at least once. What do the following statements do? double[] array; array = new double[14]; a) Create a double array containing 13 elements. b) Create a double array containing 14 elements. c) Create a double array containing 15 elements. d) Declare but do not create a double array. b) Create a double array containing 14 elements. Consider the code segment below. if ( gender == 1 ) { if ( age >= 65 ) ++seniorFemales; } // end if This segment is equivalent to which of the following? a. if ( gender == 1 || age >= 65 ) ++seniorFemales; b. if ( gender == 1 && age >= 65 ) ++seniorFemales; c. if ( gender == 1 AND age >= 65 ) ++seniorFemales; d. if ( gender == 1 OR age >= 65 ) ++seniorFemales; b. if ( gender == 1 && age >= 65 )++seniorFemales; Which is a correct static method call of Math class method sqrt? a. sqrt( 900 );. b. math.sqrt( 900 );. c. Math.sqrt( 900 );. d. Math math = new Math(); math.sqrt( 900 );. c. Math.sqrt( 900 );. Declaring main as ________ allows the JVM to invoke main without creating an instance of the class. a. public. b. void. c. static. d. final. c. static. Which statement is not true; a. The Java API consists of packages. b. The Java API helps programmers avoid "reinventing the wheel." c. The Java API consists of import declarations. d. The class javax.swing.JApplet is part of the Java API. c. The Java API consists of import declarations. Which statement below could be used to simulate the outputs of rolling a six-sided die? Suppose randomNumbers is a Random object. a. 1 + randomNumbers.nextInt( 6 ); b. 1 + randomNumbers.nextInt( 2 ); c. 6 + randomNumbers.nextInt( 1 ); d. 3 + randomNumbers.nextInt( 3 ); a. 1 + randomNumbers.nextInt( 6 ); Suppose method1 is declared as; void method1 ( int a, float b ) Which of the following methods correctly overloads method1? a. void method2 ( int a, float b ). b. void method2 ( float a, int b ). c. void method1 ( float a, int b ). d. void method1 ( int b, float a ). c. void method1 ( float a, int b ). Consider the array: s[ 0 ] = 7 s[ 1 ] = 0 s[ 2 ] = -12 s[ 3 ] = 9 s[ 4 ] = 10 s[ 5 ] = 3 s[ 6 ] = 6 The value of s[ s[ 6 ] - s[ 5 ] ] is; a. 0. b. 3. c. 9. d. 0. c. 9. Consider the program below: public class Test { public static void main( String[] args ) { int[] a; a = new int[ 10 ]; for ( int i = 0; i < a.length; i++ ) a[ i ] = i + 2; int result = 0; for ( int i = 0; i < a.length; i++ ) result += a[ i ]; System.out.printf( "Result is: %dn", result ); } // end main } // end class Test The output of this program will be: a. Result is: 62. b. Result is: 64. c. Result is: 65. d. Result is: 67. c. Result is: 65. Consider array items, which contains the values 0, 2, 4, 6 and 8. If method changeArray is called with the method call changeArray( items, items[ 2 ] ), what values are stored in items after the method has finished executing? public static void changeArray( int[] passedArray, int value ) { passedArray[ value ] = 12; value = 5; } // end method changeArray a. 0, 2, 5, 6, 12. b. 0, 2, 12, 6, 8. c. 0, 2, 4, 6, 5. d. 0, 2, 4, 6, 12. d. 0, 2, 4, 6, 12. Which of the following should usually be private? a. Methods. b. Constructors. c. Variables (or fields). d. All of the above. c. Variables (or fields). When should a program explicitly use the this reference? a. Accessing a private variable. b. Accessing a public variable. c. Accessing a local variable. d. Accessing a field that is shadowed by a local variable. c. Accessing a local variable. When implementing a method, use the class's set and get methods to access the class's ________ data. a. public. b. private. c. protected. d. All of the above. b. private. Attempting to access an array element out of the bounds of an array, causes a(n)________________________. a) ArrayOutOfBoundsException b) ArrayElementOutOfBoundsException c) ArrayIndexOutOfBoundsException d) ArrrayException c) ArrayIndexOutOfBoundsException Assume array items contains the values 0, 2, 4, 6 and 8. Which of the following set of statements uses the enhanced for loop to display each value in array items? a) for ( int i : items )    System.out.printf( "%dn", items[ i ] ); b) for ( int i : items )    System.out.printf( "%dn", i); c) for ( int i = 0 : items.length )    System.out.printf( "%dn", items[ i ] ); d) for ( int i = 0 : items.length;i++ )   System.out.printf( "%dn",items[ i ] ); b) for ( int i : items )   System.out.printf( "%dn", i); Consider the array declaration: int s[] = {7, 0, -12, 9, 10, 3, 6}; What is the value of  s[ s[ 6 ] - s[ 5 ] ] a) 0 b) 3 c) 9 d) -12 c) 9 A programmer must do the following before using an array: a) declare then reference the array. b) create then declare the array. c) create then reference the array. d) declare then create the array. d) declare then create the array. Which expression adds 1 to the element of array arrayName at index i? a) ++arrayName[ i ] b) arrayName++[ i ] c) arrayName[ i++ ] a) ++arrayName[ i ] Sending a message to an object means that; a) You call a method of the object b) You access a variable of the object c) Both a and b d) Neither a nor b a) You call a method of the object Textbook - Page 12 Consider integer array values, which contains 5 elements. Which statements successfully swap the contents of the array at index 3 and index 4? a) values[ 3 ] = values[ 4 ];     values[ 4 ] = values[ 3 ]; b) values[ 4 ] = values[ 3 ];     values[ 3 ] = values[ 4 ]; c) int temp = values[ 3 ];     values[ 3 ] = values[ 4 ];     values[ 4 ] = temp; d) int temp = values[ 3 ];     values[ 3 ] = values[ 4 ];     values[ 4 ] = values[ 3 ]; c) int temp = values[ 3 ];        values[ 3 ] = values[ 4 ];        values[ 4 ] = temp; Assume a class, Book, has been defined. Which set of statements creates an array of Book objects? a) Book books[];     books = new Book[ numberElements ]; b) Book books[];     books = new Book()[ numberElements ]; c) new Book() books[];     books = new Book[ numberElements ]; a) Book books[];        books = new Book[ numberElements ]; Which statement below initializes array items to contain 3 rows and 2 columns? a) int items[][] = { { 2, 4 }, { 6, 8 }, { 10, 12 } }; b) int items[][] = { { 2, 6, 10 }, { 4, 8, 12 } }; c) int items[][] = { 2, 4 }, { 6, 8 }, { 10, 12 }; d) int items[][] = { 2, 6, 10 }, { 4, 8, 12 }; a) int items[][] = { { 2, 4 }, { 6, 8 }, { 10, 12 } }; A well designed method; a) performs multiple unrelated tasks b) repeats code found in other methods c) contains thousands of lines of code d) performs a single, well-defined task d) performs a single, well-defined task Which of the following sets of statements creates a multidimensional array with 3 rows, where the first row contains 1 value, the second row contains 4 items and the final row contains 2 items? a) int items[][]; items = new int[ 3 ][ ? ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ]; b) int items[][]; items = new int[ 3 ][ ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ]; c) int items[][]; items = new int[ ? ][ ? ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ]; d) int items[][]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ]; b) int items[][]; items = new int[ 3 ][ ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ]; When an argument is passed by reference: a) a copy of the argument’s value is passed to the called method. b) changes to the argument do not affect the original variable’s value in the caller. c) the called method can access the argument’s value in the caller directly and modify that data. d) the original value is removed from memory. c) the called method can access the argument’s value in the caller directlyand modify that data. In array items, which expression below retrieve the value at row 3 and column 5? a) items[ 3 ].[ 4 ] b) items[ 3[ 4 ] ] c) items[ 3 ][ 4 ] d) items[ 3, 4 ] c) items[ 3 ][ 4 ] Attributes of a class are also known as; a) constructors b) local variables c) fields d) classes c) fields What it the output of the following program? public class TestApp {      public static void main(String[] args) {           int items[] = {0, 2, 4, 6, 8};           outputArray(items );           changeArray(items, items[ 2 ] );           outputArray(items );            } // end method main      public static void outputArray( int passedArray[] )      {           for ( int item : passedArray )               System.out.printf("%d   ", item);               System.out.println();      } // end method outputArray      public static void changeArray( int passedArray[], int value )      {           passedArray[ value ] = 12;           value = 5;      } // end method changeArray } // end class TestApp 0   2   4  6   8 0   2   4  6   12 Which of the following should usually be private? a. Methods. b. Constructors. c. Variables (or fields). d. All of the above. c. Variables (or fields). Which of the following statements is true? a.Methods and instance variables can both be either public or private. b.Information hiding is achieved by restricting access to class members via keyword public. c.The private members of a class are directly accessible to the client of a class. d.None of the above is true. a.Methods and instance variables can both be either public or private. What type of methods allow a client of a class to assign values to a private instance variable? a) get methods b) replace methods c) assign methods d) set methods d) set methods When should a program explicitly use the this reference? a. Accessing a private variable. b. Accessing a public variable. c. Accessing a local variable. d. Accessing a field that is shadowed by a local variable. c. Accessing a local variable. Having a this reference allows: a. A method to refer explicitly to the instance variables and other methods of the object on which the method was called. b. A method to refer implicitly to the instance variables and other methods of the object on which the method was called. c. An object to reference itself. d. All of the above. d. All of the above. A constructor cannot: a. Be overloaded. b. Initialize variables to their defaults. c. Specify return types or return values. d. Have the same name as the class. c. Specify return types or return values. Constructors: a. Initialize instance variables. b. When overloaded, can have identical argument lists. c. When overloaded, are selected by number and types of parameters. d. a and c. d. a and c. Declaring main as _____________ allows the JVM to invoke main without creating an instance of the class. a) public b) void c) static d) final c) static When implementing a method, use the class’s set and get methods to access the class’s ________ data. a. public. b. private. c. protected. d. All of the above. b. private. Which statement is false? a.The compiler always creates a default constructor for a class. b. If a class has constructors, but none of the public constructors are no-argument constructors, and a program attempts to call a no-argument constructor to initialize an object of he class, a compilation error occurs. c. A constructor can be called with no arguments only if the class does not have any constructors or if the class has a public no-argument constructor. d. Java allows other methods of the class besides its constructors to have the same name as the class and to specify return types. a.The compiler always creates a default constructor for a class. Not using set and get methods is: a. A syntax error. b. A logic error. c. Not good program design. d. None of the above. c. Not good program design. Using public set methods provides data integrity if: a. The instance variables are public. b. The instance variables are private. c. The methods perform validity checking. d. Both b and c. d. Both b and c. Composition is sometimes referred to as a(n) ________. a. is-a relationship. b. has-a relationship. c. have-a relationship. d. one-to-many relationship. b. has-a relationship. Static class variables: a. Are final. b. Are public. c. Are private. d. Are shared by all objects of a class. d. Are shared by all objects of a class. Which of the following is not true? a) A static method must be used to access private static instance variables. b) A static method has no this reference. c) A static method can be accessed even when no objects of its class have been instantiated. d) A static method can call instance methods directly. d. A static method can call instance methods directly. Instance variables declared final do not or cannot: a.Use the principle of least privilege. b. Be initialized. c. Be modified. d. Cause syntax errors if used as a left-hand value. c. Be modified. The term information hiding refers to: a) public methods. b) Hiding implementation details from clients of a class. c) Accessing static class members. d) The process of releasing an object for garbage collection. b) Hiding implementation details from clients of a class. A package is: a) A directory structure used to organize classes and interfaces. b) A mechanism for software reuse. c) A group of related classes and interfaces. d) All of the above. d) All of the above. The import declaration import *; ________. a) causes a compilation error. b) imports all classes in the library. c) imports the default classes in the library. d) imports the classes in package java.lang. a) causes a compilation error. Write a program in which you have a class called Balloon. This class is for drawing some balloons on a given environment. It will have x,y,w,h  and color variables and a draw method. Another class of type JFrame will have a Balon inside a JPanel, and a button. When you click the button the balloon will expand 10 pixel and change its color to another random color. public class Balloon {                int x,y,w,h;                Color c;   public Balloon(int          x1,int y1,int w1,int h1, Color c1) {          x=x1;              y=y1;              w=w1;              h=h1;          c=c1;   }   public void draw(Graphics g){                 g.setColor(c);                   g.drawRect(x,y,w,h);                   g.drawOval(x,y,w,h);                     g.fillOval(x,y,w,h);   } } import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class mm extends JFrame            implements   ActionListener{                     Balloon b;                     JButton jb;                     JPanel jp;                     Random rn;              public mm(){                    jp=new JPanel();                    jb=new JButton("ok");                    rn=new Random();                   Container c =                             this.getContentPane();          c.setLayout(new GridLayout(1,2));                    jb.addActionListener(this);                    c.add(jb);         b=new Balloon(100,100,100,100,new Color(255,0,0));         c.add(jp);         jp.setBackground(Color.WHITE);         setSize(500,500);         setVisible(true);         // new Timer(1000,this).start(); } public void paint(Graphics g){             super.paint(g);             int re=rn.nextInt(256);             int gr=rn.nextInt(256);             int bl=rn.nextInt(256);         b.c=new Color(re,gr,bl);         b.draw(jp.getGraphics()); } public void actionPerformed(ActionEvent e){         b.w=b.w+20;         b.h=b.h+20;         repaint(); }  public static void main(String[] args) {         mm f=new mm(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  } } An argument type followed by a(n)____________________ in a method's parameter list indicates that the method receives a variable number of arguments of that particular type. a. square brackets ([]). b. ellipsis (...). c. varargs keyword. d. All of the above are acceptable to indicate a variable number of arguments. b. ellipsis (...). Which command below runs TestProgram, and passes in the values files.txt and 3? a. java TestProgram files.txt 3. b. java TestProgram files.txt, 3. c. java TestProgram "files.txt", "3". d. java TestProgram (the arguments files.txt and 3 were passed in when the application was compiled). a. java TestProgram files.txt 3. Which method call converts the value in variable stringVariable to an integer? a. Convert.toInt( stringVariable ). b. Convert.parseInt( stringVariable ). c. Integer.parseInt( stringVariable ). d. Integer.toInt( stringVariable ). c. Integer.parseInt( stringVariable ). Class Arrays methods sort, binarySearch, equals and fill are overloaded for primitive-type arrays and Object arrays. In addition, methods __________ and __________ are overloaded with generic versions. a. sort, binarySearch. b. sort, fill. c. binarySearch, equals. d. binarySearch, fill. c. binarySearch, equals. Class Arrays provides method __________ for comparing arrays. a. compare. b. compares. c. equal. d. equals. d. equals. Class ________ represents a dynamically resizable array-like data structure. a. Array. b. ArrayList. c. Arrays. d. None of the above. b. ArrayList. Which of the following is false? a. The size of an ArrayList can be determined via its length instance variable. b. The size of an ArrayList can be determined via its size method. c. You can add a new item to the end of an ArrayList with its add method. d. You can get an item from a specified index in an ArrayList with its get method. a. The size of an ArrayList can be determined via its length instance variable. Which method sets the background color of a JPanel? a. setBack. b. setBackground. c. setBackgroundColor. d. setColor. b. setBackground. Which of the following statements about an arc is false? a. An arc is a section of an oval. b. The sweep is the amount of arc to cover. c. Method drawArc draws the edges of an arc. d. The fillArc method draws an oval, with the section that is an arc filled in. d. The fillArc method draws an oval, with the section that is an arc filled in. Arrays are:  a. variable-length entities. b. fixed-length entities. c. data structures that contain up to 10 related data items. d. used to draw a sequence of lines, or "rays." b. fixed-length entities. Which of the following statements about arrays are true? A. An array is a group of variables containing values that all have the same type. B. Elements are located by index or subscript. C. The length of an array c is determined by the expression c.length();. D. The zeroth element of array c is specified by c[ 0 ]. a. A, C, D. b. A, B, D. c. C, D. d. A, B, C, D. b. A, B, D. Consider the array: s[ 0 ] = 7 s[ 1 ] = 0 s[ 2 ] = -12 s[ 3 ] = 9 s[ 4 ] = 10 s[ 5 ] = 3 s[ 6 ] = 6 The value of s[ s[ 6 ] - s[ 5 ] ] is: a. 0. b. 3. c. 9. d. 0. c. 9. A programmer must do the following before using an array: a. declare then reference the array. b. create then declare the array. c. create then reference the array. d. declare then create the array. d. declare then create the array. Consider the code segment below. Which of the following statements is false? int[] g; g = new int[ 23 ]; a. The first statement declares an array reference. b. The second statement creates the array. c. g is a reference to an array of integers. d. The value of g[ 3 ] is -1. d. The value of g[ 3 ] is -1. Which of the following statements about creating arrays and initializing their elements is false? a. The new keyword should be used to create an array. b. When an array is created, the number of elements must be placed in square brackets following the type of element being stored. c. The elements of an array of integers have a value of null before they are initialized. d. A for loop is commonly used to set the values of the elements of an array. c. The elements of an array of integers have a value of null before they are initialized. What do the following statements do?      double[] array;      array = new double[ 14 ]; a. Create a double array containing 13 elements. b. Create a double array containing 14 elements. c. Create a double array containing 15 elements. d. Declare but do not create a double array. b. Create a double array containing 14 elements. Which of the following initializer lists would correctly set the elements of array n? a. int[] n = { 1, 2, 3, 4, 5 };. b. array n[ int ] = { 1, 2, 3, 4, 5 };. c. int n[ 5 ] = { 1; 2; 3; 4; 5 };. d. int n = new int( 1, 2, 3, 4, 5 );. a. int[] n = { 1, 2, 3, 4, 5 };. Constant variables also are called ________________. a. write-only variables. b. finals. c. named constants. d. All of the above. c. named constants. Which of the following will not produce a compiler error? a. Changing the value of a constant after it is declared. b. Changing the value at a given index of an array after it is created. c. Using a final variable before it is initialized. d. All of the above will produce compiler errors. b. Changing the value at a given index of an array after it is created. Consider the class below: public class Test { public static void main( String[] args ) {     int[] a = { 99, 22, 11, 3, 11, 55, 44, 88, 2, -3 };     int result = 0;         for ( int i = 0; i < a.length; i++ )             {                  if ( a[ i ] > 30 ) result += a[ i ]; } // end for System.out.printf( "Result is: %dn", result ); } // end main } // end class Test The output of this Java program will be: a. Result is: 280. b. Result is: 154. c. Result is: 286. d. Result is: 332. c. Result is: 286. Which flag in a format specifier indicates that values with fewer digits than the field width should begin with a leading 0? a. p. b. l. c. w. d. 0. d. 0. Invalid possibilities for array indices include _______________.  a. Positive integers. b. Negative integers. c. Zero. d. None of the above. b. Negative integers. Which of the following statements is false? a. An exception indicates a problem that occurs while a program executes.  b. Exception handling enables you to create fault-tolerant programs that can resolve (or handle) exceptions—in many cases, this allows a program to continue executing as if no problems were encountered.  c. The catch block contains the code that might throw an exception, and the try block contains the code that handles the exception if one occurs.  d. Inside the catch block, you can use the parameter's identifier to interact with a caught exception object. c. The catch block contains the code that might throw an exception, and the try block contains the code that handles the exception if one occurs. Which of the following tasks cannot be performed using an enhanced for loop? a. Calculating the product of all the values in an array. b. Displaying all even element values in an array. c. Comparing the elements in an array to a specific value. d. Incrementing the value stored in each element of the array. d. Incrementing the value stored in each element of the array. Which statement correctly passes the array items to method takeArray? Array items contains 10 elements. a. takeArray( items[] ). b. takeArray( items ). c. takeArray( items[ 9 ] ). d. Arrays cannot be passed to methods—each item must be sent to the method separately. b. takeArray( items ). Consider array items, which contains the values 0, 2, 4, 6 and 8. If method changeArray is called with the method call changeArray( items, items[ 2 ] ), what values are stored in items after the method has finished executing? public static void changeArray( int[] passedArray, int value ) { passedArray[ value ] = 12;                          value = 5; } // end method changeArray a. 0, 2, 5, 6, 12. b. 0, 2, 12, 6, 8. c. 0, 2, 4, 6, 5. d. 0, 2, 4, 6, 12. d. 0, 2, 4, 6, 12. When an argument is passed by reference: a. a copy of the argument's value is passed to the called method. b. changes to the argument do not affect the original variable's value in the caller. c. the called method can access the argument's value in the caller directly and modify that data. d. the original value is removed from memory. c. the called method can access the argument's value in the caller directly and modify that data. What kind of application tests a class by creating an object of that class and calling the class's methods? a. Pseudo application. b. Debugger. c. Tester. d. Test harness. d. Test harness. In Java, multidimensional arrays: a. are not directly supported. b. are implemented as arrays of arrays. c. are often used to represent tables of values. d. All of the above. d. All of the above. An array with m rows and n columns is not: A. An m-by-n array. B. An n-by-m array. C. A two-dimensional array. D. A dual-transcripted array. a. A and C. b. A and D. c. B and D. d. B and C. c. B and D. Which statement below initializes array items to contain 3 rows and 2 columns? a. int[][] items = { { 2, 4 }, { 6, 8 }, { 10, 12 } };. b. int[][] items = { { 2, 6, 10 }, { 4, 8, 12 } };. c. int[][] items = { 2, 4 }, { 6, 8 }, { 10, 12 };. d. int[][] items = { 2, 6, 10 }, { 4, 8, 12 };. a. int[][] items = { { 2, 4 }, { 6, 8 }, { 10, 12 } };. Superclass methods with this level of access cannot be called from subclasses. a. private. b. public. c. protected. d. package. a. private. Private fields of a superclass can be accessed in a subclass; a. by calling private methods declared in the superclass. b. by calling public or protected methods declared in the superclass. c. directly. d. All of the above. b. by calling public or protected methods declared in the superclass. For which of the following would polymorphism not provide a clean solution? a. A billing program where there is a variety of client types that are billed with different fee structures. b. A maintenance log program where data for a variety of types of machines is collected and maintenance schedules are produced for each machine based on the data collected. c. A program to compute a 5% savings account interest for a variety of clients. d. An IRS program that maintains information on a variety of taxpayers and determines who to audit based on criteria for classes of taxpayers. c. A program to compute a 5% savings account interest for a variety of clients. Because there is only one kind of calculation then there is no need for polymorphism. A(n) ______ class cannot be instantiated. a. final. b. concrete. c. abstract. d. polymorphic. c. abstract. Consider classes A, B and C, where A is an abstract superclass, B is a concrete class that inherits from A, and C  is a concrete class that inherits from B. Class A declares abstract method originalMethod, implemented in class Which of the following statements is true of class C? a. Method originalMethod cannot be overridden in class C—once it has been implemented in concrete class B, it is implicitly final. b. Method originalMethod must be overridden in class C, or a syntax error will occur. c. If method originalMethod is not overridden in class C but is called by an object of class C, an error occurs. d. None of the above. d. None of the above. An interface may contain: a. private static data and public abstract methods. b. only public abstract methods. c. public static final data and public abstract methods. d. private static data and public final methods. c. public static final data and public abstract methods. Which of the following is not true of heavyweight components? a. AWT components are not heavyweight components. b. Several Swing components are heavyweight components. c. The look-and-feel may vary across platforms. d. The functionality may vary across platforms. a. AWT components are not heavyweight components. Which of the following statements makes the text in a JTextField uneditable? a. textField.setEditable( true ); b. textField.setEditable( false ); c. textField.setUneditable( true ); d. textField.setUneditable( false ); b. textField.setEditable( false ); The GUI event with which the user interacts is the; a. event effector. b. event container. c. event raiser. d. event source. d. event source. Which method determines if a JCheckBox is selected? a. isSelected. b. getSelected. c. selected. d. None of the above. a. isSelected. Which of the following objects cannot trap mouse events? a. JTextField. b. ButtonGroup. c. JButton. d. JComponent. b. ButtonGroup. The Shift key is a(n) ______ key. a. modifier. b. action. c. output. d. None of the above. a. modifier. The class GridLayout constructs ______ to hold components. a. a horizontal grid with one row. b. a vertical grid with one column. c. a grid with multiple rows and columns. d. a square grid with the same number of rows as columns. c. a grid with multiple rows and columns. A String constructor cannot be passed variables of type: a. char arrays. b. int arrays. c. byte arrays. d. Strings. b. int arrays. The statement; s1.equalsIgnoreCase( s4 ) is equivalent to which of the following? a. s1.regionMatches( true, 0, s4, 0, s4.length() ); b. s1.regionMatches( 0, s4, 0, s4.length() ); c. s1.regionMatches( 0, s4, 0, s4.length ); d. s1.regionMatches( true, s4, 0, s4.length ); a. s1.regionMatches( true, 0, s4, 0, s4.length() ); Given the following declarations: StringBuilder buf; StringBuilder buf2 = new StringBuilder(); String c = new String( "test" ); Which of the following is not a valid StringBuilder constructor? a. buf = new StringBuilder(); b. buf = new StringBuilder( buf2, 32 ); c. buf = new StringBuilder( 32 ); d. buf = new StringBuilder( c ); b. buf = new StringBuilder( buf2, 32 ); Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1, delimArg ); For the String line1 to have 4 tokens, delimArg should be; a. String delimArg = "+="; b. String delimArg = "123" c. String delimArg = "c+"; d. String delimArg = " "; a. String delimArg = "+="; Intermixing program and error-handling logic; a. increases a program’s performance, because the program does not need to perform tests to determine whether a task executed correctly and the next task can be performed. b. should be used in place of exception handling where possible. c. can degrade a program’s performance, because the program must perform (potentially frequent) tests to determine whether a task executed correctly and the next task can be performed. d. None of the above. c. can degrade a program’s performance, because the program must perform (potentially frequent) tests to determine whether a task executed correctly and the next task can be performed. All exception classes inherit, either directly or indirectly, from; a. class Error. b. class RuntimeException. c. class Throwable. d. None of the above. c. class Throwable. Which of the following statements is false? a. The smallest data item a computer can assume is the value 0 or the value 1. b. The term “bit” is short for “byte digit.” c. Java uses the Unicode character set. d. A record is typically composed of several fields. b. The term “bit” is short for “byte digit.” When all the contents of a file are truncated, this means that; a. the data in the file is saved to a backup file. b. the file is deleted. c. a FileNotFoundException occurs. d. All the data in the file is discarded. d. All the data in the file is discarded. Which of the following classes enable input and output of entire objects to or from a file? A. SerializedInputStream B. SerializedOutputStream C. ObjectInputStream D. ObjectOutputStream E. Scanner F. Formatter a. A and B. b. C and D. c. C, D, E, F. d. E and F. b. C and D. Given the following variables; char c = 'c'; int i = 10; double d = 10; long l = 1; String s = "Hello"; Which of the following will compile without error? 1) c=c+i; 2) s+=i; 3) i+=s; 4) c+=s; 2) s+=i; Only a String acts as if the + operator were overloaded class C {    public static void main(String[] args) {                        int i1=1;                switch(i1){                 case 1: System.out.println("one");                 case 2: System.out.println("two");               case 3: System.out.println("three"); }}} What is the result of attempting to compile and run the program? 1. prints one two three 2. prints one 3. compile time error 4. Runtime exceptionf 5. None of the above 1. prints one two three There is no break statement in case 1 so it causes the lower case statements to execute regardless of their values class C{             int i;           public static void main (String[] args) {              int i; //1              private int a = 1; //2              protected int b = 1; //3              public int c = 1; //4          System.out.println(a+b+c); //5 }} 1. compiletime error at lines 1,2,3,4,5 2. compiletime error at lines 2,3,4,5 3. compiletime error at lines 2,3,4 4. prints 3 5. None of the above 2. compiletime error at lines 2,3,4,5 The access modifiers public, protected and private, can not be applied to variables declared inside methods. What will happen when you attempt to compile and run this code? abstract class Base{      abstract public void myfunc();      public void another(){        System.out.println("Another method"); }} public class Abs extends Base{       public static void main(String argv[]){              Abs a = new Abs();              a.amethod();              }              public void myfunc(){                   System.out.println("My Func");                    }              public void amethod(){                 myfunc(); }} 1) The code will compile and run, printing out the words "My Func" 2) The compiler will complain that the Base class has non abstract methods 3) The code will compile but complain at run time that the Base class has non abstract methods 4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to looove it 1) The code will compile and run, printing out the words "My Func" A class that contains an abstract method must be declared abstract itself, but may contain non abstract methods. What will happen when you attempt to compile and run this code? public class MyMain{      public static void main(String argv){          System.out.println("Hello cruel world"); }} 1) The compiler will complain that main is a reserved word and cannot be used for a class 2) The code will compile and when run will print out "Hello cruel world" 3) The code will compile but will complain at run time that no constructor is defined 4) The code will compile but will complain at run time that main is not correctly defined 4) The code will compile but will complain at run time that main is not correctly defined In this example the parameter is a string not a string array as needed for the correct main method Which of the following are Java modifiers? 1) public 2) private 3) friendly 4) transient 5) vagrant 1) public, 2) private, 4) transient The keyword transient is easy to forget as is not frequently used. Although a method may be considered to be friendly like in C++ it is not a Java keyword. What will happen when you attempt to compile and run this code? class Base{         abstract public void myfunc();           public void another(){           System.out.println("Another method"); }}       public class Abs extends Base{              public static void main(String argv[])             {              Abs a = new Abs();              a.amethod();              }        public void myfunc(){                      System.out.println("My func"); }        public void amethod(){               myfunc(); }} 1) The code will compile and run, printing out the words "My Func" 2) The compiler will complain that the Base class is not declared as abstract. 3) The code will compile but complain at run time that the Base class has non abstract methods 4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to looove it 2) The compiler will complain that the Base class is not declared as abstract. If a class contains abstract methods it must itself be declared as abstract Why might you define a method as native? (More than one answer maybe true). 1) To get to access hardware that Java does not know about 2) To define a new data type such as an unsigned integer 3) To write optimised code for performance in a language such as C/C++ 4) To overcome the limitation of the private scope of a method 1) To get to access hardware that Java does not know about 3) To write optimised code for performance in a language such as C/C++ What will happen when you attempt to compile and run this code?         class Base{ public final void amethod(){         System.out.println("amethod"); }} public class Fin extends Base{       public static void main(String argv[]){                 Base b = new Base();                 b.amethod(); }} 1) Compile time error indicating that a class with any final methods must be declared final itself 2) Compile time error indicating that you cannot inherit from a class with final methods 3) Run time error indicating that Base is not defined as final 4) Success in compilation and output of "amethod" at run time. 4) Success in compilation and output of "amethod" at run time. A final method cannot be ovverriden in a sub class, but apart from that it does not cause any other restrictions. What will happen when you attempt to compile and run this code? public class Mod{ public static void main(String argv[]){ }         public static native void amethod(); } 1) Error at compilation: native method cannot be static 2) Error at compilation native method must return value 3) Compilation but error at run time unless you have made code containing native amethod available 4) Compilation and execution without error 4) Compilation and execution without error It would cause a run time error if you had a call to amethod though. What will happen when you attempt to compile and run this code? private class Base{} public class Vis{                 transient int iVal;         public static void main(String elephant[]){ }} 1) Compile time error: Base cannot be private 2) Compile time error indicating that an integer cannot be transient 3) Compile time error transient not a data type 4) Compile time error malformed main method 1)Compile time error: Base cannot be private A top level (non nested) class cannot be private. What happens when you attempt to compile and run these two files in the same directory? //File P1.java package MyPackage; class P1{ void afancymethod(){         System.out.println("What a fancy method"); }} //File P2.java public class P2 extends P1{   public static void main(String argv[]){             P2 p2 = new P2();             p2.afancymethod(); }} 1) Both compile and P2 outputs "What a fancy method" when run 2) Neither will compile 3) Both compile but P2 has an error at run time 4) P1 compiles cleanly but P2 has an error at compile time 4) P1 compiles cleanly but P2 has an error at compile time The package statement in P1.java is the equivalent of placing the file in a different directory to the file P2.java and thus when the compiler tries to compile P2 an error occurs indicating that superclass P1 cannot be found. You want to find out the value of the last element of an array. You write the following code. What will happen when you compile and run it.? public class MyAr{ public static void main(String argv[]){           int[] i = new int[5];           System.out.println(i[5]); }} 1) An error at compile time 2) An error at run time 3) The value 0 will be output 4) The string "null" will be output 2) An error at run time This code will compile, but at run-time you will get an ArrayIndexOutOfBounds exception. This becuase counting in Java starts from 0 and so the 5th element of this array would be i[4]. Remember that arrays will always be initialized to default values wherever they are created. You want to loop through an array and stop when you come to the last element. Being a good java programmer and forgetting everything you ever knew about C/C++ you know that arrays contain information about their size. Which of the following can you use? 1)myarray.length(); 2)myarray.length; 3)myarray.size 4)myarray.size(); 2)myarray.length; The String class has a length() method to return the number of characters. I have sometimes become confused between the two. What best describes the appearance of an application with the following code? import java.awt.*; public class FlowAp extends Frame{ public static void main(String argv[]){       FlowAp fa=new FlowAp();         fa.setSize(400,300);       fa.setVisible(true); } FlowAp(){       add(new Button("One"));       add(new Button("Two"));       add(new Button("Three"));       add(new Button("Four")); }//End of constructor }//End of Application 1) A Frame with buttons marked One to Four placed on each edge. 2) A Frame with buutons marked One to four running from the top to bottom 3) A Frame with one large button marked Four in the Centre 4) An Error at run time indicating you have not set a LayoutManager 3) A Frame with one large button marked Four in the Centre The default layout manager for a Frame is the BorderLayout manager. This Layout manager defaults to placing components in the centre if no constraint is passed with the call to the add method. How do you indicate where a component will be positioned using Flowlayout? 1) North, South,East,West 2) Assign a row/column grid reference 3) Pass a X/Y percentage parameter to the add method 4) Do nothing, the FlowLayout will position the component 4) Do nothing, the FlowLayout will position the component How do you change the current layout manager for a container? 1) Use the setLayout method 2) Once created you cannot change the current layout manager of a component 3) Use the setLayoutManager method 4) Use the updateLayout method 1) Use the setLayout method Which of the following are fields of the GridBagConstraints class? 1) ipadx 2) fill 3) insets 4) width 1) ipadx, 2) fill, 3) insets What most closely matches the appearance when this code runs? import java.awt.*; public class CompLay extends Frame{ public static void main(String argv[]){       CompLay cl = new CompLay(); } CompLay(){            Panel p = new Panel();                  p.setBackground(Color.pink);            p.add(new Button("One"));            p.add(new Button("Two"));            p.add(new Button("Three"));            add("South",p);            setLayout(new FlowLayout());            setSize(300,300);            setVisible(true); }} 1) The buttons will run from left to right along the bottom of the Frame 2) The buttons will run from left to right along the top of the frame 3) The buttons will not be displayed 4) Only button three will show occupying all of the frame 2) The buttons will run from left to right along the top of the frame The call to the setLayout(new FlowLayout()) resets the Layout manager for the entire frame and so the buttons end up at the top rather than the bottom. Which statements are correct about the anchor field? (More than one answer may apply). 1) It is a field of the GridBagLayout manager for controlling component placement 2) It is a field of the GridBagConstraints class for controlling component placement 3) A valid setting for the anchor field is GridBagConstraints.NORTH 4) The anchor field controls the height of components added to a container 2) It is a field of the GridBagConstraints class for controlling component placement 3) A valid settting for the anchor field is GridBagconstraints.NORTH What will happen when you attempt to compile and run the following code? public class Bground extends Thread{ public static void main(String argv[]){          Bground b = new Bground();        b.run();        } public void start(){        for (int i = 0; i <10; i++){              System.out.println("Value of i = " + i); } }} 1) A compile time error indicating that no run method is defined for the Thread class 2) A run time error indicating that no run method is defined for the Thread class 3) Clean compile and at run time the values 0 to 9 are printed out 4) Clean compile but no output at runtime 4) Clean compile but no output at runtime This is a bit of a sneaky one as I have swapped around the names of the methods you need to define and call when running a thread. If the for loop were defined in a method called public void run() and the call in the main method had been to b.start() The list of values from 0 to 9 would have been output. True/False:  When using the GridBagLayout manager, each new component requires a new instance of the GridBagConstraints class. False You can re-use the same instance of the GridBagConstraints when added successive components. How does the set collection deal with duplicate elements? 1) An exception is thrown if you attempt to add an element with a duplicate value 2) The add method returns false if you attempt to add an element with a duplicate value 3) A set may contain elements that return duplicate values from a call to the equals method 4) Duplicate values will cause an error at compile time 2) The add method returns false if you attempt to add an element with a duplicate value I find it a surprise that you do not get an exception. What can cause a thread to stop executing? 1) The program exits via a call to System.exit(0); 2) Another thread is given a higher priority 3) A call to the thread's stop method. 4) A call to the halt method of the Thread class? 1) The program exits via a call to exit(0); 2) The priority of another thread is increased 3) A call to the stop method of the Thread class Note that this question asks what can cause a thread to stop executing, not what will cause a thread to stop executing. Java threads are somewhat platform dependent and you should be carefull when making assumptions about Thread priorities. On some platforms you may find that a Thread with higher priorities gets to "hog" the processor. You can read up on this in more detail at http://java.sun.com/docs/books/tutorial/essential/threads/priority.html For a class defined inside a method, what rule governs access to the variables of the enclosing method? 1) The class can access any variable 2) The class can only access static variables 3) The class can only access transient variables 4) The class can only access final variables 4) The class can only access final variables Under what circumstances might you use the yield method of the Thread class? 1) To call from the currently running thread to allow another thread of the same or higher priority to run 2) To call on a waiting thread to allow it to run 3) To allow a thread of higher priority to run 4) To call from the currently running thread with a parameter designating which thread should be allowed to run 1) To call from the currently running thread to allow another thread of the same or higher priority to run Option 3 looks plausible but there is no guarantee that the thread that grabs the cpu time will be of a higher priority. It will depend on the threading algorithm of the Java Virtual Machine and the underlying operating system What will happen when you attempt to compile and run the following code? public class Hope{    public static void main(String argv[]){              Hope h = new Hope(); }     protected Hope(){           for(int i =0; i <10; i ++){                System.out.println(i); } }} 1) Compilation error: Constructors cannot be declared protected 2) Run time error: Constructors cannot be declared protected 3) Compilation and running with output 0 to 10 4) Compilation and running with output 0 to 9 4) Compilation and running with output 0 to 9 What will happen when you attempt to compile and run the following code? public class MySwitch{ public static void main(String argv[]){            MySwitch ms= new MySwitch();          ms.amethod(); } public void amethod(){      int k=10;             switch(k){             default: //Put the default at the bottom, not here             System.out.println("This is the default output");             break;      case 10: System.out.println("ten");      case 20: System.out.println("twenty");              break; } }} 1) None of these options 2) Compile time error target of switch must be an integral type 3) Compile and run with output "This is the default output" 4) Compile and run with output of the single line "ten" 1) None of these options Because of the lack of a break statement after the break 10; statement the actual output will be"ten" followed by "twenty" The design pattern known as "Model View Controller" (MVC), originated with what programming language? Smalltalk What part of the MVC design pattern is responsible for mapping user actions or events to queries or state changes of the model? Controller What part of the MVC design pattern is responsible for maintaining the current state of the system or application and comprises the underlying data representation of the system? Model What part of the MVC design pattern is responsible for what the user sees (what is presented to the user)? The View Which of the following is the correct syntax for suggesting that the JVM performs garbage collection? 1) System.free(); 2) System.setGarbageCollection(); 3) System.out.gc(); 4) System.gc(); 4) System.gc(); What will happen when you attempt to compile and run the following code? public class As{          int i = 10;          int j;          char z= 1;          boolean b;     public static void main(String argv[]){              As a = new As();              a.amethod();              }              public void amethod(){                  System.out.println(j);                  System.out.println(b); }} 1) Compilation succeeds and at run time an output of 0 and false 2) Compilation succeeds and at run time an output of 0 and true 3) Compile time error b is not initialised 4) Compile time error z must be assigned a char value 1) Compilation succeeds and at run time an output of 0 and false The default value for a boolean declared at class level is false, and integer is 0; What will happen when you attempt to compile and run the following code with the command line "hello there"? public class Arg{ String[] MyArg;     public static void main(String argv[]){        MyArg=argv;        }      public void amethod(){          System.out.println(argv[1]); }} 1) Compile time error 2) Compilation and output of "hello" 3) Compilation and output of "there" 4) None of the above 1) Compile time error You will get an error saying something like "Cant make a static reference to a non static variable". Note that the main method is static. Even if main was not static the array argv is local to the main method and would thus not be visible within amethod. What will happen when you attempt to compile and run the following code? public class StrEq{ public static void main(String argv[]){      StrEq s = new StrEq();      }       private StrEq(){             String s = "Marcus";             String s2 = new String("Marcus");                if(s == s2){         System.out.println("we have a match");                          }else{         System.out.println("Not equal"); } }} 1) Compile time error caused by private constructor 2) Output of "we have a match" 3) Output of "Not equal" 4) Compile time error by attempting to compare strings using == 3) Output of "Not equal" Despite the actual character strings matching, using the == operator will simply compare memory location. Because the one string was created with the new operator it will be in a different location in memory to the other string. What will happen when you attempt to compile and run the following code? import java.io.*; class Base{    public void amethod()throws FileNotFoundException{} } public class ExcepDemo extends Base{      public static void main(String argv[]){             ExcepDemo e = new ExcepDemo(); } public void amethod(){} protected ExcepDemo(){          try{                DataInputStream din = new                DataInputStream(System.in);                System.out.println("Pausing");                din.readByte();                System.out.println("Continuing");                this.amethod();       }catch(IOException ioe) {} }} 1) Compile time error caused by protected constructor 2) Compile time error caused by amethod not declaring Exception 3) Runtime error caused by amethod not declaring Exception 4) Compile and run with output of "Pausing" and "Continuing" after a key is hit 4) Compile and run with output of "Pausing" and "Continuing" after a key is hit An overriden method in a sub class must not throw Exceptions not thrown in the base class. In the case of the method, amethod, it throws no exceptions and will thus compile without complain. There is no reason that a constructor cannot be protected. What will happen when you attempt to compile and run this program? public class Outer{ public String name = "Outer"; public static void main(String argv[]){              Inner i = new Inner();              i.showName(); }//End of main        private class Inner{          String name =new String("Inner");                void showName(){                     System.out.println(name);                        }                }//End of Inner class } 1) Compile and run with output of "Outer" 2) Compile and run with output of "Inner" 3) Compile time error because Inner is declared as private 4) Compile time error because of the line creating the instance of Inner 4) Compile time error because of the line creating the instance of Inner This looks like a question about inner classes but it is also a reference to the fact that the main method is static and thus you cannot directly access a non static method. The line causing the error could be fixed by changing it to say; Inner i = new Outer().new Inner(); Then the code would compile and run producing the output "Inner". What will happen when you attempt to compile and run this code? //Demonstration of event handling import java.awt.*; import java.awt.event.*; public class MyWc extends Frame implements WindowListener{ public static void main(String argv[]){        MyWc mwc = new MyWc();        }        public void windowClosing(WindowEvent we){         System.exit(0);       }//End of windowClosing        public void MyWc(){             setSize(300,300);             setVisible(true); }}//End of class 1) Error at compile time 2) Visible Frame created that that can be closed 3) Compilation but no output at run time 4) Error at compile time because of comment before import statements 1) Error at compile time If you implement an interface you must create bodies for all methods in that interface. This code will produce an error saying that MyWc must be declared abstract because it does not define all of the methods in WindowListener. Option 4 is nonsense as comments can appear anywhere. Option 3 suggesting that it might compile but not produce output is meant to mislead on the basis that what looks like a constructor is actually an ordinary method as it has a return type. Which option most fully describes will happen when you attempt to compile and run the following code? public class MyAr{       public static void main(String argv[]) {                MyAr m = new MyAr();                m.amethod();       }       public void amethod(){                static int i;                System.out.println(i); }} 1) Compilation and output of the value 0 2) Compile time error because i has not been initialized 3) Compilation and output of null 4) Compile time error   4) Compile time error An error will be caused by attempting to define an integer as static within a method. The lifetime of a field within a method is the duration of the running of the method. A static field exists once only for the class. An approach like this does work with Visual Basic. Which of the following will compile correctly? 1) short myshort = 99S; 2) String name = 'Excellent tutorial Mr Green'; 3) char c = 17c; 4) int z = 015; 4) int z = 015; The letters c and s do not exist as literal indicators and a String must be enclosed with double quotes, not single as in this case. Which of the following are Java key words? 1) double 2) Switch 3) then 4) instanceof 1) double, 4) instanceof Note the upper case S on switch means it is not a keyword and the word then is part of Visual Basic but not Java. Also, instanceof looks like a method but is actually a keyword, What will be output by the following line? System.out.println(Math.floor(-2.1)); 1) -2 2) 2.0 3) -3 4) -3.0 4) -3.0 Given the following main method in a class called Cycle and a command line of; java Cycle one two what will be output? public static void main(String bicycle[]){     System.out.println(bicycle[0]); } 1) None of these options 2) cycle 3) one 4) two 3) one Command line parameters start from 0 and from the first parameter after the name of the compile (normally Java) Which of the following statements are true? 1) At the root of the collection hierarchy is a class called Collection 2) The collection interface contains a method called enumerator 3) The interator method returns an instance of the Vector class 4) The Set interface is designed for unique elements 4) The Set is designed for unique elements. Collection is an interface, not a class. The Collection interface includes a method called iterator. This returns an instance of the Iterator class which has some similarities with Enumerators.The name set should give away the purpose of the Set interface as it is analogous to the Set concept in relational databases which implies uniquness. Which of the following statements are correct? 1) If multiple listeners are added to a component only events for the last listener added will be processed 2) If multiple listeners are added to a component the events will be processed for all but with no guarantee in the order 3) Adding multiple listeners to a comnponent will cause a compile time error 4) You may remove as well add listeners to a component. 2) If multiple listeners are added to a component the events will be processed for all but with no guarantee in the order 4) You may remove as well add listeners to a component. It ought to be fairly intuitive that a component ought to be able to have multiple listeners. After all, a text field might want to respond to both the mouse and keyboard Given the following code; class Base{} public class MyCast extends Base{       static boolean b1=false;       static int i = -1;       static double d = 10.1;       public static void main(String argv[]){             MyCast m = new MyCast();             Base b = new Base();             //Here }} Which of the following, if inserted at the comment //Here, will allow the code to compile and run without error? 1) b=m; 2) m=b; 3) d =i; 4) b1 =i; 1) b=m; and/or  3) d =i; You can assign up the inheritance tree from a child to a parent but not the other way without an explicit casting. A boolean can only ever be assigned a boolean value. Which of the following statements about threading are true? 1) You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable 2) You can obtain a mutually exclusive lock on any object 3) A thread can obtain a mutually exclusive lock on an object by calling a synchronized method on that object. 4) Thread scheduling algorithms are platform dependent 2) You can obtain a mutually exclusive lock on any object 3) A thread can obtain a mutually exclusive lock on an object by calling a synchronized method on that object.  4) Thread scheduling algorithms are platform dependent Yes that says dependent and not independent. Your chief Software designer has shown you a sketch of the new Computer parts system she is about to create. At the top of the hierarchy is a Class called Computer and under this are two child classes. One is called LinuxPC and one is called WindowsPC. The main difference between the two is that one runs the Linux operating System and the other runs the Windows System (of course another difference is that one needs constant re-booting and the other runs reliably). Under the WindowsPC are two Sub classes one called Server and one Called Workstation. How might you appraise your designers work? 1) Give the goahead for further design using the current scheme 2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type 3) Ask for the option of WindowsPC to be removed as it will soon be obsolete 4) Change the hierarchy to remove the need for the superfluous Computer Class. 2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type This question is about the requirement to understand the difference between the "is-a" and the "has-a" relationship. Where a class is inherited you have to ask if it represents the "is-a" relationship. As the difference between the root and the two children are the operating system you need to ask are Linux and Windows types of computers.The answer is no, they are both types of Operating Systems. So option two represents the best of the options. You might consider having operating system as an interface instead but that is another story. Of course there are as many ways to design an object hierarchy as ways to pronounce Bjarne Strousjoup, but this is the sort of answer that Sun will proabably be looking for in the exam. Questions have been asked in discussion forums if this type of question really comes up in the exam. I think this is because some other mock exams do not contain any questions like this. I assure you that this type of question can come up in the exam. These types of question are testing your understanding of the difference between the is-a and has-a relationship in class design. Which of the following statements are true? 1) An inner class may be defined as static 2) There are NO circumstances where an inner class may be defined as private 3) A programmer may only provide one constructor for an anonymous class 4) An inner class may extend another class 1) An inner class may be defined as static 4) An inner class may extend another class A static inner class is also sometimes known as a top level nested class. There is some debate if such a class should be called an inner class. I tend to think it should be on the basis that it is created inside the opening braces of another class. How could a programmer provide a constructor for an anonymous class?. Remember a constructor is a method with no return type and the same name as the class. Inner classes may be defined as private What will happen when you attempt to compile and run the following code? int Output=10; boolean b1 = false; if((b1==true) && ((Output+=10)==20)){   System.out.println("We are equal "+Output);   }else {   System.out.println("Not equal! "+Output); } 1) Compile error, attempting to peform binary comparison on logical data type 2) Compilation and output of "We are equal 10" 3) Compilation and output of "Not equal! 20" 4) Compilation and output of "Not equal! 10" 4) Compilation and output of "Not equal! 10" The output will be "Not equal 10".  This illustrates that the Output +=10 calculation was never performed because processing stopped after the first operand was evaluated to be false. If you change the value of b1 to true processing occurs as you would expect and the output is "We are equal 20";. Given the following variables which of the following lines will compile without error? String s = "Hello"; long l = 99; double d = 1.11; int i = 1; int j = 0; 1) j= i <<s; 2) j= i<<j; 3) j=i<<d; 4) j=i<<l; 2) j= i<<j;   4) j=i<<l; What will be output by the following line of code? System.out.println(010|4); 1) 14 2) 0 3) 6 4) 12 4) 12 As well as the binary OR objective this questions requires you to understand the octal notation which means that the leading letter zero (not the letter O)) means that the first 1 indicates the number contains one eight and nothing else. Thus this calculation in decimal means;  8|4 To convert this to binary means 10000100----1100;  Which is 12 in decimal.  The | bitwise operator means that for each position where there is a 1, results in a 1 in the same position in the answer. Given the following variables; char c = 'c'; int i = 10; double d = 10; long l = 1; String s = "Hello"; Which of the following will compile without error? 1) c=c+i; 2) s+=i; 3) i+=s; 4) c+=s; 2) s+=i; Only a String acts as if the + operator were overloaded Which of the following will compile without error? 1) File f = new File("/","autoexec.bat"); 2) DataInputStream d = new      DataInputStream(System.in); 3) OutputStreamWriter o = new      OutputStreamWriter(System.out); 4) RandomAccessFile r = new      RandomAccessFile("OutFile"); 1) File f = new File("/","autoexec.bat"); 2) DataInputStream d = new       DataInputStream(System.in); 3) OutputStreamWriter o = new       OutputStreamWriter(System.out); Option 4, with the RandomAccess file will not compile because the constructor must also be passed a mode parameter which must be either "r" or "rw" Given the folowing classes which of the following will compile without error? interface IFace{} class CFace implements IFace{} class Base{} public class ObRef extends Base{         public static void main(String argv[]){             ObRef ob = new ObRef();             Base b = new Base();             Object o1 = new Object();             IFace o2 = new CFace(); }} 1) o1=o2; 2) b=ob; 3) ob=b; 4) o1=b;   1) o1=o2; 2) b=ob; 4) o1=b; Given the following code what will be the output? class ValHold{              public int i = 10; } public class ObParm{ public static void main(String argv[]){         ObParm o = new ObParm();         o.amethod();         }         public void amethod(){                 int i = 99;                 ValHold v = new ValHold();                 v.i=30;                 another(v,i);                 System.out.print( v.i );           }//End of amethod public void another(ValHold v, int i){                i=0;                v.i = 20;                ValHold vh = new ValHold();                v = vh;                System.out.print(v.i);      System.out.print(i);      }//End of another} 1) 10030 2) 20030 3) 209930 4) 10020 4) 10020 In the callanother(v,i);  A reference to v is passed and thus any changes will be intact after this call. Given the following class definition, which of the following methods could be legally placed after the comment; //Here public class Rid{         public void amethod(int i, String s){}         //Here } 1)public void amethod(String s, int i){} 2)public int amethod(int i, String s){} 3)public void amethod(int i, String mystring){} 4) public void Amethod(int i, String s) {} 1) public void amethod(String s, int i){} 4) public void Amethod(int i, String s) {} Overloaded methods are differentiated only on the number, type and order of parameters, not on the return type of the method or the names of the parameters. Given the following class definition which of the following can be legally placed after the comment line; //Here ? class Base{ public Base(int i){} } public class MyOver extends Base{    public static void main(String arg[]){            MyOver m = new MyOver(10);            }            MyOver(int i){                    super(i);            }            MyOver(String s, int i){                    this(i);                     //Here }} 1) MyOver m = new MyOver(); 2) super(); 3) this("Hello",10); 4)Base b = new Base(10); 4)Base b = new Base(10); Any call to this or super must be the first line in a constructor. As the method already has a call to this, no more can be inserted. Given the following class definition, which of the following statements would be legal after the comment //Here ? class InOut{ String s= new String("Between");           public void amethod(final int iArgs){               int iam;                  class Bicycle{                      public void sayHello(){                      //Here                      }            }//End of bicycle class       }//End of amethod public void another(){                   int iOther; }} 1) System.out.println(s); 2) System.out.println(iOther); 3) System.out.println(iam); 4) System.out.println(iArgs); 1) System.out.println(s); 4) System.out.println(iArgs); A class within a method can only see final variables of the enclosing method. However it the normal visibility rules apply for variables outside the enclosing method. Which of the following are methods of the Thread class? 1) yield() 2) sleep(long msec) 3) go() 4) stop() 1) yield(),  2) sleep,  4) stop() Note, the methods stop and suspend have been deprecated with the Java2 release, and you may get questions on the exam that expect you to know this. Check out the Java2 Docs for an explanation Which of the following methods are members of the Vector class and allow you to input a new element? 1) addElement 2) insert 3) append 4) addItem 1) addElement Which of the following statements are true? 1) Adding more classes via import statements will cause a performance overhead, only import classes you actually use. 2) Under no circumstances can a class be defined with the private modifier 3) A inner class may under some circumstances be defined with the protected modifier 4) An interface cannot be instantiated 3)A inner class may under some circumstances be defined with the protected modifier 4) An interface cannot be instantiated The import statement allows you to use a class directly instead of fully qualifying it with the full package name, adding more classess with the import statement does not cause a runtime performance overhead. An inner class can be defined with the protected modifier, though I am not certain why you would want to do it. An inner class can be defined with the private modifier. Which of the following are correct event handling methods? 1) mousePressed(MouseEvent e){} 2) MousePressed(MouseClick e){} 3) functionKey(KeyPress k){} 4) componentAdded(ContainerEvent e){} 1) mousePressed(MouseEvent e){} 4) componentAdded(ContainerEvent e){} Which of the following are methods of the Collection interface? 1) iterator 2) isEmpty 3) toArray 4) setText 1) iterator 2) isEmpty 3) toArray Which of the following best describes the use of the synchronized keyword? 1) Allows two process to run in paralell but to communicate with each other 2) Ensures only one thread at a time may access a method or object 3) Ensures that two or more processes will start and end at the same time 4) Ensures that two or more Threads will start and end at the same time 2) Ensures only one thread at a time may access a method or object What is an 'instanceof' ?  A. An operator and keyword  B. A methods in object A. An operator and keyword True/False:  Primitive datatypes are allocated on a stack True Following code will result in: int a1 = 5; double a2 = (float)a1; A) Runtime error B) No errors B) No errors What is a function in terms of Computer Science ?  A. A group of code lines that performs a specific task  B. Something that contains an 'init' A. A group of code lines that performs a specific task Integer a = new Integer(2); Integer b = new Integer(2); What happens when you do if (a==b)? A) True B) False B) False What is Java (in regard to Computer Science) ? A) A MVC B) An object-oriented programming language c) A subset of C B) An object-oriented programming language How can you prevent a member variable from becoming serialized?  A. By marking it volatile  B. By marking it transient B. By marking it transient True/False:  By default, all primitive-type variables are serializable. True In a serializable class, every instance variable must be serializable.  Non-serializable instance variables must be declared transient to indicate that they should be ignored during the serialization process. What is MVC (Model View Controller)? MVC is an architectural pattern which separates the representation and user interaction. It’s divided into three broader sections, Model, View, and Controller. Below is how each one of them handles the task. 1) The View is responsible for the look and feel. 2) Model represents the real world object and provides data to the View. 3) The Controller is responsible for taking the end user request and loading the appropriate Model and View. Which design pattern is most likely to be used as a proxy? a) business delegate b) data access object c) model-view-controller d) value object c) model-view-controller Which design pattern reduces the number of remote network method calls required to obtain the attribute values from the entity beans? a) business delegate b) data access object c) model-view-controller d) value object c) model-view-controller Which design pattern that usually is a good candidate to work with entity beans, becomes less useful when a cache is used to persist data? a) business delegate b) data access object c) model-view-controller d) value object c) model-view-controller Which of the following is illegal?  int i = 32; float f = 45.0; double d = 45.0; float f = 45.0; public class Test { static int age; public static void main (String args []) { age = age + 1; System.out.println("The age is " + age); }} Which statement is true? a) Compiles and runs with no output b) Compiles and runs printing out The age is 1 c) Compiles but generates a runtime error d) Does not compile e) Compiles but generates a compile time error b) Compiles and runs printing out The age is 1 Which of the following are correct?  a) 128 >> 1 gives 64 b) 128 >>> 1 gives 64 c) 128 >> 1 gives -64 d) 128 >>> 1 gives -64 a) 128 >> 1 gives 64 b) 128 >>> 1 gives 64 Which of the following return true?  a) "john" == "john" b) "john".equals("john") c) "john" = "john" d) "john".equals(new Button("john")) a) "john" == "john" b) "john".equals("john") Which of the following are so called "short circuit" logical operators?  a) & b) || c) && d) | b) || c) && Which of the following are acceptable? a) Object o = new Button("A"); b) Frame f = new Panel(); c) Boolean flag = true; d) Boolean flag = true; e) Panel p = new Applet(); a) Object o = new Button("A"); e) Panel p = new Applet(); public class Test { static int total = 10; public static void main (String args []) { new Test(); } public Test () { System.out.println("In test"); System.out.println(this); int temp = this.total; if (temp > 5) { System.out.println(temp); }}}  Which of the following is true? a) The compiler reports an error at line 2 b) The class will not compile c) The value 10 is one of the elements printed to the standard output d) The compiler reports an error at line 9 e) The class compiles but generates a runtime error c) The value 10 is one of the elements printed to the standard output Which of the following is correct:  a) String temp [] = new String {"j" "a" "z"}; b) String temp [] = { "j " " b" "c"}; c) String temp = {"a", "b", "c"}; d) String temp [] = {"a", "b", "c"}; d) String temp [] = {"a", "b", "c"}; What is the correct declaration of an abstract method that is intended to be public? a) public abstract void add(); b) public abstract void add() {} c) public virtual add(); d) public abstract add(); a) public abstract void add(); Under what situations do you obtain a default constructor?  a) When you define any class b) When the class has no other constructors c) When you define at least one constructor b) When the class has no other constructors Which of the following are acceptable to the Java compiler?  a) if (2 == 3) System.out.println("Hi"); b) if (2 = 3) System.out.println("Hi"); c) if (true) System.out.println("Hi"); d) if (2 != 3) System.out.println("Hi"); e) if (aString.equals("hello"))         System.out.println("Hi"); a) if (2 == 3) System.out.println("Hi"); c) if (true) System.out.println("Hi"); d) if (2 != 3) System.out.println("Hi"); e) if (aString.equals("hello"))               System.out.println("Hi"); Assuming a method contains code which may raise an Exception (but not a Runtime Exception), what is the correct way for a method to indicate that it expects the caller to handle that exception? a) throw Exception b) throws Exception c) new Exception d) Don't need to specify anything b) throws Exception public void divide(int a, int b) { try { int c = a / b; } catch (Exception e) { System.out.print("Exception "); } finally { System.out.println("Finally"); }  Which is true? a) Prints out: Finally b) Prints out: Exception c) Prints out: Exception Finally d) No output c) Prints out: Exception Finally Which of the following statements is correct for a method which is overriding the following method: public void add(int a) {...} a) the overriding method must return void b) the overriding method must return int c) the overriding method can return whatever it likes a) the overriding method must return void Given the following classes defined in separate files: class Vehicle { public void drive() { System.out.println("Vehicle: drive"); }} class Car extends Vehicle { public void drive() { System.out.println("Car: drive"); }} public class Test { public static void main (String args []) { Vehicle v; Car c; v = new Vehicle(); c = new Car(); v.drive(); c.drive(); v = c; v.drive(); }} What will be the effect of compiling and running this class Test?  a) Generates a Compiler error on the statement v= c b) Generates runtime error on the statement v= c c) Prints out:       Vehicle : drive      Car : drive      Car : drive d) Prints out:       Vehicle : drive      Car : drive      Vehicle : drive c) Prints out:            Vehicle : drive           Car : drive           Car : drive Where in a constructor, can you place a call to a constructor defined in the super class?  a) The first statement in the constructor b) The last statement in the constructor c) You can't call super in a constructor d) Anywhere a) The first statement in the constructor Which variables can an inner class access from the class which encapsulates it?  a) All static variables b) All final variables c) All instance variables d) Only final instance variables e) Only final static variables a) All static variables b) All final variables c) All instance variables What class must an inner class extend? a) The top level class b) The Object class c) Any class or interface d) It must extend an interface c) Any class or interface In the following code, which is the earliest statement, where the object originally held in e, may be garbage collected? public class Test {  public static void main (String args []) {      Employee e = new Employee("Bob", 48);      e.calculatePay();  System.out.println(e.printDetails());  e = null;  e = new Employee("Denise", 36);  e.calculatePay();  System.out.println(e.printDetails());  } } a) Line 7 b) Line 8 c) Line 10 d) Line 11 e) Never a) Line 7 What is the name of the interface that can be used to define a class that can execute within its own thread? a) Run b) Runnable c) Thread d) Threadable e) Executable b) Runnable What is the name of the method used to schedule a thread for execution? a) init(); b) start(); c) run(); d) resume(); e) sleep(); b) start(); Which methods may cause a thread to stop executing?  a) sleep(); b) stop(); c) yield(); d) wait(); e) notify(); a) sleep(); b) stop(); c) yield(); d) wait(); Which of the following methods are defined on the Graphics class:  a) drawLine(int, int, int, int) b) drawImage(Image, int, int, ImageObserver) c) add(Component); d) drawString(String, int, int) e) setVisible(boolean); a) drawLine(int, int, int, int) b) drawImage(Image, int, int, ImageObserver) d) drawString(String, int, int) Which of the following layout managers honors the preferred size of a component: a) CardLayout b) FlowLayout c) BorderLayout d) GridLayout b) FlowLayout Given the following code what is the effect of a being 5: public class Test { public void add(int a) { loop: for (int i = 1; i < 3; i++){ for (int j = 1; j < 3; j++) { if (a == 5) { break loop; } System.out.println(i * j); }}}}  a) Generate a runtime error b) Throw an ArrayIndexOutOfBoundsException c) Print the values: 1, 2, 2, 4 d) Produces no output d) Produces no output What is the effect of issuing a wait() method on an object  a) If a notify() method has already been sent to that object then it has no effect b) The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method c) An exception will be raised d) The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object. b) The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method The layout of a container can be altered using which of the following methods:  a) setLayout(aLayoutManager); b) addLayout(aLayoutManager); c) layout(aLayoutManager); d) setLayoutManager(aLayoutManager); a) setLayout(aLayoutManager); Using a FlowLayout manager, which is the correct way to add elements to a container:  a) set(component); b) add("Center", component); c) add(x, y, component); d) add(component); d) add(component); Given that a Button can generate an ActionEvent which listener would you expect to have to implement, in a class which would handle this event?  a) FocusListener b) WindowListener c) ComponentListener d) ItemListener e) ActionListener e) ActionListener Which of the following, are valid return types, for listener methods:  a) boolean b) the type of event handled c) Component d) void d) void Assuming we have a class which implements the ActionListener interface, which method should be used to register this with a Button? a) addListener(*); b) addActionListener(*); c) addButtonListener(*); d) setListener(*); b) addActionListener(*); In order to cause the paint(Graphics) method to execute, which of the following is the most appropriate method to call:  a) paint() b) repaint() c) paint(Graphics) d) update(Graphics) e) None, you should never cause paint(Graphics) to execute b) repaint() Which of the following illustrates the correct way to pass a parameter into an applet: a)  <applet code=Test.class age=33 width=100 height=100> b) <param name=age value=33> c) <applet code=Test.class name=age value=33 width=100 height=100> d) <applet Test 33> b) <param name=age value=33> Which of the following correctly illustrate how an InputStreamReader can be created:  a) new InputStreamReader(new FileInputStream("data")); b) new InputStreamReader(new BufferedReader("data")); c) new InputStreamReader(System.in); d) new InputStreamReader("data"); e) new InputStreamReader(new FileReader("data")); a) new InputStreamReader(new FileInputStream("data")); c) new InputStreamReader(System.in); What is the permanent effect on the file system of writing data to a new FileWriter("report"), given the file report already exists?  a) The data is appended to the file b) The file is replaced with a new file c) An exception is raised as the file already exists d) The data is written to random locations within the file b) The file is replaced with a new file What is the effect of adding the sixth element to a vector created in the following manner: new Vector(5, 10);  a) An IndexOutOfBounds exception is raised.  b) The vector grows in size to a capacity of 10 elements c) The vector grows in size to a capacity of 15 elements d) Nothing, the vector will have grown when the fifth element was added c) The vector grows in size to a capacity of 15 elements What is the result of executing the following code when the value of x is 2: switch (x) { case 1:System.out.println(1); case 2: case 3: System.out.println(3); case 4: System.out.println(4);  a) The value 3 is printed out b) The values 3 and 4 are printed out c) The values 1, 3 and 4 are printed out d) Nothing is printed out b) The values 3 and 4 are printed out What is the result of executing the following fragment of code: boolean flag = false; if (flag = true) { System.out.println("true"); } else { System.out.println("false"); }}  a) true is printed to standard out b) false is printed to standard out c) An exception is raised d) Nothing happens a) true is printed to standard out What is the result of executing the following Java class: import java.awt.*; public class FrameTest extends Frame { public FrameTest() { add (new Button("First")); add (new Button("Second")); add (new Button("Third")); pack(); setVisible(true); } public static void main(String args []) { new FrameTest(); }}  a) Three buttons are displayed across a window. b) Only the "second" button is displayed. c) Only the "third" button is displayed. d) Only the "first" button is displayed. e) A runtime exception is generated (no layout manager specified). c) Only the "third" button is displayed. Consider the following tags and attributes of tags: 1. CODEBASE  2. ALT  3. NAME  4. CLASS  5. JAVAC  6. HORIZONTALSPACE  7. VERTICALSPACE  8. WIDTH  9. PARAM  10. JAR Which of the above can be used within the APPLET tags? a) line 1, 2, 3  b) line 2, 5, 6, 7 c) line 3, 4, 5 d) line 8, 9, 10 e) line 8, 9 a) line 1, 2, 3  e) line 8, 9 Which of these are legal identifiers. Select the three correct answers; A) number_1 B) number_a C) $1234 D) -volatile A) number_1 B) number_a C) $1234 Which of these are not legal identifiers. Select the four correct answers; A) 1alpha B) _abcd C) xy+abc D) transient E) account-num F) very_long_name A) 1alpha C) xy+abc D) transient E) account-num Which of the following are keywords in Java. Select the two correct answers; A) friend B) NULL C) implement D) synchronized E) throws D) synchronized E) throws Which of the following are Java keywords. Select the four correct answers; A) super B) strictfp C) void D) synchronize E) instanceof A) super B) strictfp C) void E) instanceof Please note that strictfp is a new keyword in Java 2. Which of these are Java keywords. Select the five correct answers; A) TRUE  B) volatile C) transient D) native E) interface F) then G) new B) volatile C) transient D) native E) interface G) new Using up to four characters, write the Java representation of octal literal 6; Any of the following are correct answers - 06, 006, or 0006 Using up to four characters, write the Java representation of integer literal 3 in hexadecimal; Any of the following are correct answers - 0x03, 0X03, 0X3 or 0x3 Using up to four characters, write the Java representation of integer literal 10 in hexadecimal; Any of the following are correct answers - 0x0a, 0X0a, 0Xa, 0xa, 0x0A, 0X0A, 0XA, 0xA What is the minimum value of char type. Select the one correct answer; A) 0  B) -2^15 C) -2^8 D) -2^15 E) - 1 -2^16 F) -2^16 - 1 A) 0 How many bytes are used to represent the primitive data type int in Java. Select the one correct answer; A) 2  B) 4  C) 8  D) 1  E) The number of bytes to represent an int is compiler dependent. B) 4 What is the legal range of values for a variable declared as a byte. Select the one correct answer; A) 0 to 256  B) 0 to 255 C) -128 to 127 D) -128 to 128 E) -127 to 128  F) -215 to 215 - 1 C) -128 to 127 The width in bits of double primitive type in Java is --. Select the one correct answer; A) The width of double is platform dependent  B) 64  C) 128  D) 8  E) 4 B) 64 What would happen when the following is compiled and executed. Select the one correct answer;   public class Compare {    public static void main(String args[]) {        int x = 10, y;        if(x < 10)                  y = 1;        if(x>= 10) y = 2;        System.out.println("y is " + y);    } } A) The program compiles and prints y is 0 when executed.  B) The program compiles and prints y is 1 when executed.  C) The program compiles and prints y is 2 when executed.  D) The program does not compile complaining about y not being initialized.  E) The program throws a runtime exception. D) The program does not compile complaining about y not being initialized.  The variable y is getting read before being properly initialized. What would happen when the following is compiled and executed. Select the one correct answer;  class example {      int x;      int y;      String name;      public static void main(String args[]) {             example pnt = new example();             System.out.println("pnt is " + pnt.name + " " + pnt.x + " " + pnt.y);   } } A) The program does not compile because x, y and name are not initialized.  B) The program throws a runtime exception as x, y, and name are used before initialization.  C) The program prints pnt is 0 0.  D) The program prints pnt is null 0 0.  E) The program prints pnt is NULL false false D) The program prints pnt is null 0 0.  Instance variable of type int and String are initialized to 0 and null respectively. The initial value of an instance variable of type String that is not explicitly initialized in the program is --. Select the one correct answer; A) null  B) ""  C) NULL D) 0  E) The instance variable must be explicitly assigned. A) null The initial value of a local variable of type String that is not explicitly initialized and which is defined in a member function of a class. Select the one correct answer; A) null  B) ""  C) NULL  D) 0  E) The local variable must be explicitly assigned. E) The local variable must be explicitly assigned. Which of the following are legal Java programs. Select the four correct answers; A)// The comments come before the packagepackage pkg;           import java.awt.*;           class C{} B) package pkg;     import java.awt.*;     class C{} C) package pkg1;     package pkg2;     import java.awt.*;     class C{} D) package pkg;      import java.awt.*; E) import java.awt.*;     class C{} F) import java.awt.*;     package pkg;     class C {} A)// The comments come before the package    package pkg;             import java.awt.*;             class C{} B) package pkg;        import java.awt.*;        class C{} D) package pkg;           import java.awt.*; E) import java.awt.*;        class C{} Which of the following statements are correct? Select the four correct answers; A) A Java program must have a package statement.  B) A package statement if present must be the first statement of the program (barring any comments). C) If a Java program defines both a package and import statement, then the import statement must come before the package statement.  D) An empty file is a valid source file.  E) A Java file without any class or interface definitions can also be compiled.  F) If an import statement is present, it must appear before any class or interface definitions. B) A package statement if present must be the first statement of the program (barring any comments). D) An empty file is a valid source file.  E) A Java file without any class or interface definitions can also be compiled.  F) If an import statement is present, it must appear before any class or interface definitions. What would be the results of compiling and running the following class. Select the one correct answer; class test {      public static void main() {          System.out.println("test");    } } A) The program does not compile as there is no main method defined.  B) The program compiles and runs generating an output of "test"  C) The program compiles and runs but does not generate any output.  D) The program compiles but does not run. D) The program compiles but does not run. Which of these are valid declarations for the main method? Select the one correct answer; A) public void main();  B) public static void main(String args[]);  C) static public void main(String);  D) public static void main(String );  E) public static int main(String args[]); B) public static void main(String args[]); Which of the following are valid declarations for the main method. Select the three correct answers; A) public static void main(String args[]);  B) public static void main(String []args);  C) final static public void main (String args[]);  D) public static int main(String args[]);  E) public static abstract void main(String args[]); A) public static void main(String args[]);  B) public static void main(String []args);  C) final static public void main (String args[]); What happens when the following program is compiled and executed with the command - java test. Select the one correct answer; class test {     public static void main(String args[]) {          if(args.length > 0)             System.out.println(args.length);     } } A) The program compiles and runs but does not print anything.  B) The program compiles and runs and prints 0  C) The program compiles and runs and prints 1  D) The program compiles and runs and prints 2  E) The program does not compile. A) The program compiles and runs but does not print anything. What is the result of compiling and running this program? Select the one correct answer; public class test {     public static void main(String args[]) {          int i, j;          int k = 0;          j = 2;          k = j = i = 1;          System.out.println(k);   } } A) The program does not compile as k is being read without being initialized.  B) The program does not compile because of the statement k = j = i = 1;  C) The program compiles and runs printing 0.  D) The program compiles and runs printing 1.  E) The program compiles and runs printing 2. D) The program compiles and runs printing 1. What gets printed on the standard output when the class below is compiled and executed by entering "java test lets see what happens". Select the one correct answer;   public class test {     public static void main(String args[]) {       System.out.println(args[0]+"              "+args[args.length-1]);    } } A) The program will throw an ArrayIndexOutOfBounds exception.  B) The program will print "java test"  C) The program will print "java happens";  D) The program will print "test happens"  E) The program will print "lets happens" E) The program will print "lets happens" What gets printed on the standard output when the class below is compiled and executed by entering "java test lets see what happens". Select the one correct answer;   public class test {      public static void main(String args[]) {          System.out.println(args[0]+"                  "+args[args.length]);   } } A) The program will throw an ArrayIndexOutOfBounds exception.  B) The program will print "java test"  C) The program will print "java happens";  D) The program will print "test happens"  E) The program will print "lets happens" A) The program will throw an ArrayIndexOutOfBounds exception. What all gets printed on the standard output when the class below is compiled and executed by entering "java test lets see what happens". Select the two correct answers;   public class test {    public static void main(String args[]) {       System.out.println(args[0]+" " +               args.length);   } } A) java  B) test  C) lets  D) 3  E) 4  F) 5  G) 6 C) lets  E) 4 What happens when the following program is compiled and run. Select the one correct answer; public class example {       int i = 0;       public static void main(String args[]) {            int i = 1;            i = change_i(i);            System.out.println(i);        } public static int change_i(int i) {            i = 2;            i *= 2;            return i;     } } A) The program does not compile.  B) The program prints 0.  C) The program prints 1.  D) The program prints 2.  E) The program prints 4. E) The program prints 4. What happens when the following program is compiled and run. Select the one correct answer; public class example {      int i = 0;      public static void main(String args[]) {          int i = 1;          change_i(i);          System.out.println(i);     } public static void change_i(int i) {          i = 2;          i *= 2;    } } A) The program does not compile.  B) The program prints 0.  C) The program prints 1.  D) The program prints 2.  E) The program prints 4. C) The program prints 1. What happens when the following program is compiled and run. Select the one correct answer; public class example {        int i[] = {0};        public static void main(String args[]) {             int i[] = {1};             change_i(i);             System.out.println(i[0]);     }        public static void change_i(int i[]) {               i[0] = 2;               i[0] *= 2;       } } A) The program does not compile.  B) The program prints 0.  C) The program prints 1.  D) The program prints 2.  E) The program prints 4. E) The program prints 4. What happens when the following program is compiled and run. Select the one correct answer; public class example {        int i[] = {0};        public static void main(String args[]) {             int i[] = {1};             change_i(i);             System.out.println(i[0]);     }        public static void change_i(int i[]) {             int j[] = {2};             i = j;   } } A) The program does not compile.  B) The program prints 0.  C) The program prints 1.  D) The program prints 2.  E) The program prints 4. C) The program prints 1. When an unchecked exception occurs in a method but is not caught; 1. the method-call stack is "unwound." 2. the method terminates.  3. all local variables in that method go out of scope. 4. All of the above. 4. All of the above. To catch an exception, the code that might throw the exception must be enclosed in a ______________________. try block Which of the following statements is true? c) The throw statement is used to throw an exception. c) The throw statement is used to throw an exception. Chained exceptions are useful for finding out about: an original exception that was caught before the current exception was thrown. In the catch block below, what is arithmeticException? catch ( ArithmeticException arithmeticException ) {      System.err.printf( arithmeticException ); } // end catch The name of catch block's exception parameter The throws clause of a method; specifies the exceptions a method throws. All exception classes inherit, either directly or indirectly, from; a) class Error b) class RuntimeException c) class Throwable d) None of the above c) class Throwable Which of the following statements regarding the throw point of an exception is false? b) It is the initial point at which the exception occurs. b) It is the initial point at which the exception occurs. When an exception occurs it is said to have been: thrown Which of the following is true? 1. A precondition must be true when a method is invoked. 2. A postcondition must be true when a method successfully returns to its caller. 3. Both of the above. 3. Both of the above. Which of the following statements is false? a) The finally block and try block can appear in any order. a) The finally block and try block can appear in any order. Which of the following exceptions is a checked exception? a) ArithmeticException b) IOException c) RuntimeException d) InputMismatchException b) IOException Which of the following errors is synchronous? 1. Divide by zero. 2. Arithmetic overflow. 3. Unsuccessful memory allocation.  4. All of the above. 4. All of the above. Intermixing program and error-handling logic: can degrade a program's performance, because the program must perform (potentially frequent) tests to determine whether a task executed correctly and the next task can be performed. After a finally block has finished executing (and there are no exceptions to be handled): control proceeds to the first statement after the finally block. Which of the following statements is true? b) Like any other class, an exception class can contain fields and methods. b) Like any other class, an exception class can contain fields and methods. Which of the following is arranged in increasing size order? a) field, bit, file, record b) byte, file, database, record c) byte, field, file, record d) bit, field, record, file d) bit, field, record, file Which of the following statements is false? c) Exception handling can catch but not resolve exceptions. c) Exception handling can catch but not resolve exceptions. Which of the following statements is true? 1. The code in a finally block is executed only if an exception occurs.  2. The code in a finally block is executed only if an exception does not occur.  3. The code in a finally block is executed only if there are no catch blocks.  4. None of the above are true. 4. None of the above are true. An uncaught exception: Is an exception that occurs for which there are no matching catch clauses. Which of the following statements is false? d) The class Throwable provides the method getStackTrace that outputs the stack trace to the standard error stream. d) The class Throwable provides the method getStackTrace that outputs the stack trace to the standard error stream. Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1 ); int count = tok.countTokens(); The value of count is: 7 Which of the following is not a word character? A. W B. 0 C. _ D. & D. & Which of the following statements is true? c) The length of a StringBuilder cannot exceed its capacity. c) The length of a StringBuilder cannot exceed its capacity. StringBuilder objects can be used in place of String objects if: 1. The string data is not constant. 2. The string data size may grow.  3. The programs frequently perform string concatenation.  4. All of the above. 4. All of the above. Stream that input bytes from and output bytes to files are known as; a) bit-based streams b) byte-based streams c) character-based streams d) Unicode-based streams b) byte-based streams Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream . There are many byte stream classes. File I/O byte streams use FileInputStream and FileOutputStream . To find the character at a certain index position within a String, use the method: charAt, with the index as an argument. Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new      StringTokenizer(line1, delimArg ); For the String line1 to have 4 tokens, delimArg should be: String delimArg = "+="; Which of the following statements is/are true? 1. Class Matcher provides methods find, lookingAt, replaceFirst and replaceAll.  2. Method matches (from class String, Pattern or Matcher) will return true only if the entire search object matches the regular expression.  3. Methods find and lookingAt (from class Matcher) will return true if a portion of the search object matches the regular expression. 4. All of above. 4. All of above. Which of the Java strings represent the regular expression ,s*? ",s*". Given the following declaration: StringBuilder buf = new StringBuilder(); What is the capacity of buf? 16 Given the following declarations: StringBuilder buf; StringBuilder buf2 = new StringBuilder(); String c = new String( "test" ); Which of the following is not a valid StringBuilder constructor? A. buf = new StringBuilder( c );  B. buf = new StringBuilder( buf2, 32 ); 100% C. buf = new StringBuilder( 32 );  D. buf = new StringBuilder(); B. buf = new StringBuilder( buf2, 32 ); 100% Which of the following is not an application of a File object? A) Open or edit a file B) Determine if a file exists C) Determine whether a file is readable D) Determine whether a file is writeable A) Open or edit a file Which of the following statements is not equivalent to; File name = new File( "c:books2009files.txt" ); Assume we are currently in the directory c:books. a) File name = new File( "files.txt" ); a) File name = new File( "files.txt" ); Which of the following statements is true? d) Class Scanner does not provide the ability to reposition to the beginning of the file. d) Class Scanner does not provide the ability to reposition to the beginning of the file. Records in a sequential file are not usually updated in place. Instead: the entire file is usually rewritten. What happens when an end-of-file marker is reached (and the program is using an ObjectInputStream to read data from a file)? An EOFException is thrown. Instance variables that are not to be output with a Serializable object are declared using which keyword? transient. Relative paths normally start from which directory? The directory in which the application began executing. What interface must a class implement to indicate that objects of the class can be output and input as a stream of bytes? Serializable A serialized object is: an object represented as a sequence of bytes used to store the object's data in a file. Which method call enables users to specify that a user can select files and directories from a JFileChooser? A. setFileSelectionMode( FILES_OR_DIRECTORIES );  B. showOpenDialog( FILES_AND_DIRECTORIES );  C. showOpenDialog( FILES_OR_DIRECTORIES ); D. None of the above. D. None of the above. When an unchecked exception occurs in a method but is not caught: 1. the method-call stack is "unwound." 2. the method terminates.  3. all local variables in that method go out of scope. 4. All of the above. 4. All of the above. What are primitives? Primitives are the fundamental data type in Java. What type of primitive data type is " int " ? int is a primitive data type that is used to store integer values. It is the default value for whole numbers. What is the "double " primitive type used to store and is it a default? double is a primitive data type for large floating-point values. It is the default value for floating-point numbers. What is a boolean primitive type used to store? boolean is a primitive data type that is used to store true or false values. What is the char primitive data type used to store? char is a primitive data type that is used to store a single Unicode character. What is the " byte " primitive used to store? byte is a primitive used to store small numbers which are a byte (8 bits) or smaller. What is the "short" primitive used to store? short is a primitive used to store whole numbers up to 16 bits. What is the "long" primitive used to store? long is a primitive used to store large whole numbers up to 64 bits. What is the "float" primitive used to store? float is a primitive data type used to store floating-point values. What case are primitive data types ? Primitive data types all start with a lowercase letter, while classes start with an uppercase letter Each primitive data type has a corresponding this? They have a corresponding "Wrapper class". Each primitive data type has a corresponding wrapper class: Integer, Double, Boolean, Character, Byte, Short, Long, and Float. Notice the capital letters. What are objects and what defines them? Objects are more advanced data types. They may be defined by a developer or found in a built-in Java package. How are Objects initialized? Objects must be initialized by using the new keyword. What do Arrays allow you to store? Arrays allow you to store multiple variables together that can be accessed by an index. What does Enumerations allow a developer to create? "Enumerations allow a developer to create" a predefined set of constants. A variable can then be set only to one of the predefined values. Why Is Java a strongly typed language? Java is a strongly typed language because Variables must be declared as a type, and any value that is stored must be compatible with this type. Is it possible to cast a variable to a different data type? It is possible to cast a variable to a different data type. If incompatible types are cast, an exception will be thrown. What is a literal ? A literal is a value that is hard-coded in code as the value itself. What are the Java naming conventions that dictate how a "class" should be named? Java naming conventions dictate that a class should be named with the first letter capitalized, along with each sequential word in the name. What are the Java naming conventions that dictate how a "variable" should be named? Java naming conventions dictate that a variable should be named with the first letter being lowercase, and with each sequential word in the name beginning with a capital letter. True/False:  All programs have at least two threads. False True/False:  All the classes java.util.TimerTask and java.uti.Timer provide methods for requesting that the JVM generate threads to run scheduled tasks. True True/False:  Your threads can launch other threads. True True/False:  The JVM is in charge of scheduling processor time according to the priorities assigned to the threads. True True/False:  When designing a class that runs on a thread, extending Thread (as opposed to implementing Runnable) is the more flexible and usually preferred approach. False True/False:  The join method of the Thread class waits for the thread object to terminate. True True/False:  A subclass of Thread must provide an implementation of the run method because it implements the Runnable interface. True True/False:  The currentThread is the static method of the Thread class True True/False:  The sleep method of the Thread class makes the thread pause for the specified number of milliseconds. True True/False:  When a Thread object is constructed with a Runnable object as input, the Thread object uses the run method of the Runnable object True True/False:  Stopping an active thread asynchronously from the outside, by calling stop or suspend, releases all locks without giving the thread an opportunity to complete potentially critical operations. True True/False: Any thread that is executing can all interrupt on another thread. True True/False: To execute a task repeatedly, specify the period in seconds. False (It's milliseconds) True/False: Deadlock can occur when all threads are in a blocked state. True True/False: Thread-safe variables belong to one thread alone; different threads have separate copies. True True/False: Changes made to variable by another thread are called synchronous changes. False (asynchronous) True/False: Locks are the Java concept for flag maintained by the operating system. True True/False: You can call wait only from a method that own a key. False (lock) True/False: A Java application window is a frame window. True True/False: Containers are components that house other components. True True/False: GUIs use a separate thread called the event dispatched thread for drawing and forwarding all paint requests to that thread. True True/False: You create handlers for user-initiated events by defining classes that implement the listener interfaces. True True/False: The Drag and Drop API provides the ability to move data between programs created with the Java programming language. True True/False: To select a predefined strategy for positioning components in a container, set up an association between a class that extends LayoutManager or LayoutManager2 and a container. False True/False: If no listeners are registered, the event is delivered to the default listener. True True/False: Swing components separate the manipulation of data associated with a component from the rendering or graphical-representation component and its contents. True True/False: Swing uses a separable model architecture. True True/False: Swing-based applications extends the javax.swing.JFrame class True True/False: The method setDefaultCloseOperation is a member of the JFrame class. True True/False: Layout managers automate the positioning of the components within containers. True True/False: The getLocation method returns the location for the mouse event. False (getPoint) True/False: All components have the methods addFocusListener and add MouseListener. True True/False: For the listener interfaces with more than one method, you can implement the listener indirectly by extending its adapter class. True True/False: The paint and update methods provide a Graphic object as an argument of the method. True True/False: The setColor method sets the color used for subsequent drawing and fill coloring. True True/False: Only the Model layer operates on persistent data. True True/False: The properties of transactional integrity have been formalized and are known as the ACID properties. True True/False: A type 1 driver is called the JDBC-ODBC bridge. True True/False: Only type 1 drivers are portable to any JVM. False (Type 4) True/False: A connection from a DataSource object has the same type as one from a DriverManager object. True True/False: The method that issues an INSERT statement returns an integer value that indicates the number of row affected. True True/False: The return type of the method that issues an SELECT statement is int. False (ResultSet) True/False: The PreparedStatement interface extends Statement. True True/False: When designing a class that runs on a thread, extending Thread (as opposed to implementing Runnable) is the more flexible and usually preferred approach. False Can a class be declared as final? Yes, a class can be declared final; that is, the class cannot be sub-classed. This is done for security and design. Are instance variables assigned a default value? Yes, member or instance variables are always given a default value. Can you compare a boolean to an int? No, booleans are true and false keywords and nothing else. Can the access specifier for an overriding method allow more or less access than the overridden method? More. The access specifier for an overriding method can allow more, but not less, access than the overridden method. What is the difference between the default and protected access specifier? Default does not allow sub class access. Both allow package access. What are the access levels in order of most restrictive to least? Class, Package, Sub class, and World What are the access specifiers in order of most restrictive to least? Private, Default, Protected, and Public What is a JavaBean? A JavaBean is any Java class that conforms to the following rules; 1) It must have an empty constructor; a constructor that accepts no parameters. If a class has no constructors at all it can qualify as a JavaBean because the default constructor has no parameters. 2) It must have no public instance variables.  All the instance variables defined by the class must be either private or protected. 3) It must provide methods named getProperty and setProperty to get and set any properties that the class provides, except for boolean properties that use isProperty to get the property value. A class does not have to have properties to be a JavaBean but if it does then the properties have to be accessed according to this naming pattern. When you pass a variable as an argument to a method call, what are you passing? A copy of the value. You always get a copy of whatever is in the variable - either a primitive or a reference. So for objects, you get a copy of the reference. What does break do? The break statement has two forms: labeled and unlabeled. An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement. What does continue do? The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. A labeled continue statement skips the current iteration of an outer loop marked with the given label. Where can an anonymous inner class be defined? An anonymous class is an expression. So anywhere an expression is used. Can overriding methods throw different exceptions than that of the super? Overriding methods cannot throw any new or broader exception that is checked. Unchecked does not apply. Can a private method be overridden? No, but it can be re-declared in the subclass. This is not polymorphism. Does each source file need a public class in it? No What access is the generated constructor given when one is not supplied? If the class is public, then it is public. Otherwise the default constructor is default. What is the keyword transient? It marks a member variable not to be serialized when it is persisted to streams of bytes. What is the keyword native? The native keyword is applied to a method to indicate that the method is implemented in native code using JNI. Will this line compile without errors? Object obj = new Object (); Yes Will this line compile without errors? Object [ ] obj = new Object [7]; Yes Will this line compile without errors? Object obj [ ] = new Object [7]; Yes Will this line compile without errors? Object obj [ ] = {new Object(), new Object()}; Yes Will this line compile without errors? Object obj [ ] = {new Object [1], new Object [2]}; Yes Will this line compile without errors? Object [ ] obj = new Object (); No.  Incorrect because they have () instead of [] after the type. Will this line compile without errors? Object obj [ ] = new Object() ; No. Incorrect because they have () instead of [] after the type. Will this line compile without errors? Object [ ] obj = new Object [ ]; No.  Incorrect because they do not assign a size to the array. Will this line compile without errors? Object obj [ ] = new Object[ ] ; No. Incorrect because they do not assign a size to the array. Will this line compile without errors? Object [ ] obj = new Object [3](); No.  Incorrect because the () after the [] is not the correct syntax. Will this line compile without errors? Object obj [ ] = new Object [3](); No. Incorrect because the () after the [] is not the correct syntax. Will this line compile without errors? Object [8] obj = new Object [ ]; No.  Incorrect because the size is not assigned when it is declared. Will this line compile without errors? Object [7] obj = new Object [7]; No. Incorrect because the size is not assigned when it is declared. Will this line compile without errors? Object [3] obj = new Object [3]() ; No.  Incorrect because the size is in the declaration and the extra () after the [] is not the correct syntax. Will this line compile without errors? Object obj [] = new {new Object(), new Object()}; No.  Incorrect because the first new operator is being used with the {} initialization method. What best describes the result of the following code segment? The ArrayList sampleArrayList has already been declared and initialized. int i = 63; sampleArrayList.add(i); The int is converted to an Integer via auto boxing and then placed into the ArrayList. Primitives cannot be stored in an ArrayList. However, if they are placed into their primitive wrapper class they can be stored. Java will automatically make that conversion via its autoboxing feature if a primitive is placed into an ArrayList. Will this line compile without errors? double[ ][ ][ ] numbers = new double[ ][ ][ ]; No. When the new operator is used, at least one array dimension in a multi-dimensional array must be given a size. Will this line compile without errors? double[ ][ ] numbers = {{1,2,3},{7,8},{4,5,6,9}}; Yes Will this line compile without errors? double[ ][ ][ ] numbers = new double[7][ ][ ]; Yes Can a constructor have a synchronized modifier? No; they can never be synchronized. What is the output of the following code segment? int value = 1; switch (value) { case 0: System.out.println("Dog"); case 1: System.out.println("Cat"); case 1: System.out.println("Fish"); default: System.out.println("Cow"); } This will not compile because it includes a case statement with the same value twice. Can a constructor be declared static? No, constructors are for creating new instance objects. Static methods are for non-instance code, so it makes no sense to have a static constructor. Can a top-level class be marked as protected? No, a top-level class can only be marked public or default. The protected access is just for member variables and methods, and allows subclasses outside the superclass package to inherit the protected members. Can a constructor be declared private? Yes. This can be used to control the creation of the object by other less restrictive methods. True or False:  During arithmetic, when the operands are different types, the resulting type is always the widest of the two types. False, the result of an arithmetic operation on any two primitive operands will be at least an int -- even if the operands are byte and short. If break statements are not used in a switch, what will happen? Once a case statement is entered, the code will continue to execute in each case below it, until it hits a break statement. Given: public void simpleTest () { int i; System.out.println(i); } What will occur? A compiler error will occur since the value has not been initialized. Which of the following are interfaces to ArrayList?  a) List b) Map c) Queue d) RandomAccess e) Set a) List d) RandomAccess ;are interfaces to ArrayList. Fill in the blank. Import statements are ______. Required in all versions of Java. All programs can be written in terms of three types of control structures:_________, selection and repetition sequence All programs can be written in terms of three types of control structures:_________, sequence and repetition selection All programs can be written in terms of three types of control structures:_________, selection and sequence repetition This statement is used to execute one action when a condition is true and another when that condition is false; if...else Repeating a set of instructions a specific number of times is called __________ repetition. counter-controlled (or definite) When it's not known in advance how many times a set of statements will be repeated, a(n) __________ value can be used to terminate the repetition. sentinel (signal, flag or dummy) The __________ structure is built into Java; by default, statements execute in the order they appear. sequence Instance variables of types char, byte, short, int, long, float and double are all given the value __________ by default. 0 (zero) Java is a(n) ________ language; it requires all variables to have a type. strongly typed If the increment operator is ___________ to a variable, first the variable is incremented by 1, then its new value is used in the expression. prefixed True/False: An algorithm is a procedure for solving a problem in terms of the actions to execute andthe order in which they execute. True True/False: A set of statements contained within a pair of parentheses is called a block. False. (A set of statements contained within a pair of braces { and } is called a block.) True/False: A selection statement specifies that an action is to be repeated while some condition remains true. False. (A repetition statement specifies that an action is to be repeated while some condition remains true) True/False: A nested control statement appears in the body of another control statement. True True/False: Java provides the arithmetic compound assignment operators +=, -=, *=, /= and %= for abbreviating assignment expressions. True True/False:  The primitive types (Boolean, char, byte, short, int, long, float and double) are portable across only Windows platforms. False. (The primitive types (Boolean, char, byte, short, int, long, float and double) are portable across all computer platforms that support Java). True/False:  Specifying the order in which statements execute in a program is called program control. True True/False:  The unary cast operator (double) creates a temporary integer copy of its operand. False. (The unary cast operator (double) creates a temporary floating-point copy of its operand). True/False:  Instance variables of type boolean are given the value true by default. False. (Instance variables of type boolean are given the value false by default). True/False:  Pseudocode helps you think out a program before attempting to write it in a programming language. True Write four different Java statements that each add 1 to integer variable x; x = x + 1; x += 1; ++x; x++; Write Java statements to accomplish the following task: Use one statement to assign the sum of x and y to z, then increment x by 1; z = y + x++ ( z = x++ + y;) Write Java statements to accomplish the following task: Test whether variable count is greater than 10. If it is, print "Count is greater than 10". if ( count > 10 )    System.out.println( "Count is greater than 10" ); Write Java statements to accomplish the following task: Use one statement to decrement the variable x by 1, then subtract it from variable total and store the result in variable total. total -= --x; Write Java statements to accomplish the following task: Calculate the remainder after q is divided by divisor, and assign the result to q. Write this statement in two different ways q %= divisor; q = q % divisor; Write Java statements to accomplish the following task: Declare variables sum and x to be of type int int sum; int x; Write Java statements to accomplish the following task: Assign 1 to variable x x = 1; Write Java statements to accomplish the following task: Assign 0 to variable sum sum = 0; Write Java statements to accomplish the following task: Add variable x to variable sum, and assign the result to variable sum sum += x; or sum = sum + x; Write Java statements to accomplish the following task: Print "The sum is: ", followed by the value of variable sum System.out.printf( "The sum is: %dn", sum ); Identify and correct the errors in the following code: while ( c <= 5 ) { product *= c; ++c; Add a closing right brace after the statement ++c (Error: The closing right brace of the while statement's body is missing.) Identify and correct the errors in the following code: if ( gender == 1 ) System.out.println( "Woman" ); else; System.out.println( "Man" ); Remove the semicolon after else (Error: The semicolon after else results in a logic error. The second output statement will always be executed) The __________ selection statement executes an indicated action only when the condition is true. if The __________ operator and the -- operator increment and decrement a variable by 1, respectively. ++ The ++ operator and the __________ operator increment and decrement a variable by 1, respectively. -- Output of the following statements: int temp; temp = 180; while ( temp != 80 ){ if ( temp > 90 ){ System.out.print( "This porridge is too hot! " ); // cool down temp = temp - ( temp > 150 ? 100 : 20 ); } // end if else{ if ( temp < 70 ){ System.out.print("This porridge is too cold! "); // warm up temp = temp + (temp < 50 ? 30 : 20); } // end if } // end else } // end while if ( temp == 80 ) System.out.println( "This porridge is just right!" ); This porridge is too hot! This porridge is just right! Java requires all variables to have a type before they can be used in a program. For this reason, Java is referred to as a(n) __________ language. strongly typed A dangling-else can be clarified by using: braces { } How many times is the body of the loop below executed? int counter; counter = 1; while ( counter > 20 ) { // body of loop counter = counter + 1; } // end while 0 times (zero) Nothing increments counter to ever make it greater than 20. If x is currently 0, a = 0 and b = -5, what will x become after the statement is executed? if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 2 If x is currently 0, a = 1 and b = -1, what will x become after the statement is executed? if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 5 If x is currently 0, a = 5 and b = 5, what will x become after the statement is executed? if (a > 0)  if (b < 0)  x = x + 5;  else  if (a > 5)  x = x + 4; else  x = x + 3; else x = x + 2; 3 True/False:  In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably). False The empty statement is denoted with what symbol? ; True/False: The statement; if (a >= b) a++; else b--; will do the same thing as the statement; if (a < b) b--; else a++; True True/False:  The statements; x++; and ++x; will accomplish the same thing, but the statements; y = x++; and y = ++x; will not. True The value of the variables at the end of loop are: I = 5; J = 4; while (I < 10) { if ( (I % 3 == 0) || (I % 3 == 1) ) { J = J + I; } I = I + 2; } I=11,  J=20 The value of the variables I, J, K at the end of the loop are: I = 8; while (I < 10) { J = 4; while (J < 6) { K = I + J; J = J + 1; } I = I + 1; } I=10 J=6 K=14 What is output by the following Java code segment? int temp; temp = 180; if ( temp > 90 ){ System.out.println( "This porridge is too hot." ); // cool down temp = temp - ( temp > 150 ? 100 : 20 ); } // end if else { if ( temp < 70 ) { System.out.println("This porridge is too cold."); // warm up temp = temp + (temp < 50 ? 30 : 20); } // end if } // end else if ( temp == 80 ) System.out.println( "This porridge is just right!" ); "The porridge is too hot." "The porridge is just right." What is output by the following Java code segment? int temp; temp = 200; if ( temp > 90 ) System.out.println( "This porridge is too hot." ); if ( temp < 70 ) System.out.println( "This porridge is too cold." ); if ( temp == 80 ) System.out.println( "This porridge is just right!" ); "The porridge is too hot" What is the result value of c at the end of the following code segment? int c = 8; c++; ++c; c %= 5; 0 (zero) What's wrong? while( (i < 10) && (i > 24)) the test condition is always false Where can local variables declared within a method's body be used?  What is their scope? Only in that method between the line in which they were declared and the closing brace of that method. True/False:  With the conditional operator ( ?: ) the second operand is the result value if the condition evaluates to false. True True/False:  "break out value" is a term used to refer to a sentinel value that breaks out of a while loop? False Write a statement that will add 1 to x if x is positive, and subtract 1 from x if x is negative, but leave x alone if x is 0; if (x > 0) x++;    else if (x < 0) x--; Typically, ___________statements are used for counter-controlled repetition and while statements for sentinel-controlled repetition. for Typically, for statements are used for counter-controlled repetition and __________ statements for sentinel-controlled repetition. while The do... while statement tests the loop-continuation condition __________ executing the loop's body; therefore, the body always executes at least once. after The _________ statement selects among multiple actions based on the possible values of an integer variable or expression. switch The __________ statement, when executed in a repetition statement, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. continue The __________ operator can be used to ensure that two conditions are both true before choosing a certain path of execution. && If the loop-continuation condition in a for header is initially __________ the program does not execute the for statement's body. false Methods that perform common tasks and do not require objects are called _________ methods. static True/False:  The default case is required in the switch selection statement. False True/False:  The break statement is required in the last case of a switch selection statement. False True/False:  The expression; ((x > y) && (a < b)) is true if either (x > y) is true OR (a < b) is true. False True/False:  An expression containing the || operator is true if either or both of its operands is true True True/False:  The comma (,) formatting flag in a format specifier (e.g., %, 20.2f) indicates that a value should be output with a thousands separator. True True/False:  To test for a range of values in a switch statement, use a hyphen (-) between the start and the end values of the range in a case label. False True/False:  Listing cases consecutively with no statements between them enables the cases to perform the same set of statements. True Write a statement: Sum the odd integers between 1 and 99, using a for statement. Assume that the integer variables sum and count have been declared. sum =0;  for ( count =1; count <=99; count +=2 )  sum += count; Write a statement:  Calculate the value of 2.5 raised to the power of 3, using the 'pow' method double result = Math.pow(2. 5, 3 ); Write a statement:  Print the integers from 1 to 20, using a while loop and the counter variable i. Assume that i has already been declared, but not initialized. Print only 5 integers per line. i=1;  while (i<= 20 ) { System.out.print( i );  if (i% 5== 0 ) System.out.println(); else System.out.print( ' t' );  ++i; } Write a statement:  Print the integers from 1 to 20, using a for loop and the counter variable i. Assume that i has already been declared, but not initialized. Print only 5 integers per line. for (i=1;i<= 20; i++ ) { System.out.print( i ); if (i% 5 == 0 ) System.out.println();  else  System.out.print( ' t' ); } Name a common programming error where a control statement uses the '<' or '>' operator when it needed the '<=' or '>=' operator. off-by-one error True/False:  Class Math is defined in java.lang and does not require an import statement to be used by a program. True True/False:  In a do....while statement the brackets ({ }) are used after the 'do' keyword and before the 'while' keyword, then the conditional statement is added after the 'while' keyword, followed by a (;). True True or False:  A class can not implement multiple interfaces. False True or False:  An interface can inherit zero or more interfaces. An interface cannot inherit a class. True True or False:  A class that inherits another class is called a derived class or subclass. True True or False:  A class that is inherited is called a parent or base class. True True or False: Private members of a base class can be inherited in the derived class. False True or False:  A derived class can only inherit members with the default access modifier if both the base class and the derived class are in the same package. True True or False:  A class uses the keyword extends to inherit a class. True True or False: An interface uses the keyword extends to inherit another interface. True True or False: A class uses the keyword extends to implement an interface. False. It uses the keyword implements to implement an interface. True or False: An interface can extend multiple interfaces. True True or False: The method signatures of a method defined in an interface and in the class that implements the interface must match; otherwise, the class won't compile. True True or False: With inheritance, you can also refer to an object of a derived class using a variable of a base class or interface. True True or False: An object of a base class can be referred to using a reference variable of its derived class. False True or False: When an object is referred to by a reference variable of a base class, the reference variable can only access the variables and members that are defined in the base class. True True or False: When an object is referred to by a reference variable of an interface implemented by a class, the reference variable can access only the variables and methods defined in the interface. True If the class Manager extends the class Employee, and a reference variable emp of type Employee is used to refer to an object of the class Manager, what operation can be done to access the derived class variables and methods of Manager? Perform a cast operation: ((Manager)emp) True or False: If a method defines a local variable or method parameter with the same name as an instance variable, the keyword this must be used to access the instance variable in the method. True What are the conditions for a method to be polymorphic? The polymorphic methods are also called overridden methods. Overridden methods should define methods with the same name, same argument list, same list of method parameters. The return type of the overriding method can be the same, or a subclass of the return type of the overridden method in the base class, which is also known as covariant return type. Access modifiers for an overriding method can be the same or less restrictive but can't be more restrictive than the method being overridden. What conditions must a method meet to be an overridden one? A derived class is said to override a method in the base class if it defines a method with the same name, same parameter list, and same return type as in the derived class. True or False: If a method defined in a base class is overloaded in the derived classes, then these two methods (in the base class and the derived class) are called polymorphic methods. False. Only overridden methods can be called polymorphic. True or False: When implementing polymorphism with classes, a method defined in the base class may or may not be abstract. True True or False: When implementing polymorphism with interfaces, a method defined in the base interface is always abstract. True Explain "Reference Type" and "Object Type" The reference type corresponds to the type in a variable declaration. The object type corresponds to the instantiated class in an object variable declaration. So "reference type" is the LHS type and "object type" is the actual instantiated type on the RHS of an object variable declaration. True or False: The super keyword can be used to invoke super class methods in the subclass's overloaded methods? True True or False: This statement will compile "( (Object)newString.toString("Foo") )" where class NewString has overloaded method "String toString(String arg)". False. The cast to Object will fail to compile since the Object class does not have a toString(String) method. True or False: The reference type determines which members of a variable object are accessible True. Only those members allowing access according to their access modifiers will be available to be called. Furthermore, only those available methods are candidates for polymorphic calls. True or False: A class with a private constructor can be inherited. False True or False: The invocation of the base class' default constructor occurs automatically unless we use the super keyword to invoke an alternative base class constructor. True Can a subclass override a method and declare fewer thrown exceptions than the superclass method? Yes, it is legal. The overriding method does not have to declare "throws" on checked exceptions declared by the super class. For overloaded methods, is it the reference type or dynamic runtime object type that determinesl which method gets called? The reference type (not the object type) determines which overloaded method is invoked! True or False: constructors are inherited by the subclass. False. Never. What is the order of execution of instance initializers and constructors-in base and subclasses? Constructors first or initializers? Each class will have its initializers called first, before the constructor. The super class constructor will be called first, implicitly or excplicitly, before the subclass. Can instance initializers be inherited by a derived class? No. The instance initializers can't be defined with any explicit access. They can only be defined using the 'default' access. Also, instance initializers aren't inherited by derived class. They execute when a class is instantiated. What is the access modifier for the default constructor? The default constructor is the no-arg one provided by the JVM. It will be assigned the same access modifier as the specified for the class itself. When can a child class in another package access a protected member in the parent class? Only when the child tries to access it own variable, not variable of other instance True or False: An abstract method can not be overridden. False. Abstract methods are meant to be overridden by subclasses. When are static instance blocks executed in an objects lifecycle? Immediately after the call to super's constructor and before the instance constructor's code. Blocks are called in top to bottom order. True or False: You can define only one variable argument in a parameter list, and it should be the final variable in the parameter list. If these two rules aren't followed, your code won't compile. True True of False: It is valid to have code that can be executed only after a return statement. False. The class will fail to compile. What is an overloaded method? Overloaded methods accept different lists of arguments. The argument lists can differ by: - Changes in the number of parameters that are accepted - Changes in the types of parameters that are accepted - Changes in the positions of parameters that are accepted True or False: Methods can be defined as overloaded methods if they differ only in their return types or access modifiers. False Define Constructor. Constructors have the same name as the class, and they create and return an instance of the class in which they are defined. They don't specify a return type—not even void. What are the three steps to reading contents of a file in the Java IO file management system? open, read, close What is the import format for file management including BufferedReader? import java.io.*; What is the syntax of the contractor for buffered reader called rd? BufferedReader rd = new BufferedReader(new FileReader("text.txt")); What is the standard idiom or line of code that closes a BufferedReader rd after reading the contents? rd.close(); What are two different ways of instantiating Buffered readers/writers? Chained constructors: new BufferedReader(new FileReader(new File("foo.txt"))); Files util: Files.newBufferedWriter(myPath, Charset.forName("UTF-8"), new OpenOption[]{StandardOpenOption.APPEND,StandardOpenOption.DSYNC}) True or False: Once created there is no way to change the file or directory that the File object represents. True. Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. The path variable of the File class has no setter, it is set only in the constructor. What attributes are supported by the BasicFileAttributeView.class? Name / Type "lastModifiedTime" FileTime "lastAccessTime" FileTime "creationTime" FileTime "size" Long "isRegularFile" Boolean "isDirectory" Boolean "isSymbolicLink" Boolean "isOther" Boolean "fileKey" Object What attributes are supported by the DosFileAttribuesView.class? Name / Type readonly Boolean hidden Boolean system Boolean archive Boolean Discuss the class hierarchy of RandomAccessFile; RandomAccessFile does not extend from InputStream or OutputStream. But it does implement java.io.DataOutput and java.io.DataInput interfaces (and Closeable and AutoCloseable interfaces as well). If a class includes a package statement, where must it be placed? The first statement of the class file What are the two ways a class can use another packages classes? 1. By declaring an import statement of the fully qualified package + class name 2. By delcaring a variable of the class type using the fully qualifed package + class name True or False: comments can appear anywhere in a class file, including before the package statement. True How is the state and behavior of a Java class defined? State is defined through the instance variables or attributes. Behavior is defined through methods. True or False: A Java source code file can defined more than one public class or interface? False True or False: If a public class or interface is defined in a Java source code file, then the name of that filemust match the name of the public class or interface. True In the world of computer programming and design patterns, who were the "gang of four"? Design Patterns: Elements of Reusable Object-Oriented Software is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides with a foreword by Grady Booch. The book is divided into two parts, with the first two chapters exploring the capabilities and pitfalls of object-oriented programming, and the remaining chapters describing 23 classic software design patterns. The book includes examples in C++ and Smalltalk. In their book, the Gang of Four outlined how many different design patterns? 23 According to the Gang of Four, what two design techniques are outlines to lead to good object-oriented software design? "Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18) "Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20) What are the 3 primary areas of focus for Object Oriented Programming (OOP)? Encapsulation Inheritance Polymorphism With polymorphism we can design and implement systems that are easily ________________. extensible. New classes can be added with little or no modification to the general portions of the program, as long as the new classes are part of the inheritance hierarchy that the program processes generically. The only parts of a program that must be altered to accommodate new classes are those that require direct knowledge of the new classes that we add to the hierarchy. True/False:  Abstract classes cannot be used to instantiate objects - abstract classes are incomplete. True Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects; otherwise, these subclasses, too, will be abstract. Classes that can be used to instantiate objects are called ______________________. concrete classes Which UML document specifies the purpose of an application/system and what it must do? A requirements document specifies the purpose of an application/system and what it must do. What UML document models the interactions between a system's clients and its use cases? A use case diagram models the interactions between a system’s clients and its use cases. It shows the kinds of interactions users have with a system without providing the details. Often accompanied by informal text that gives more detail—like the text that appears in the requirements document. Produced during the analysis stage of the software life cycle. A _____________ is a set of component that interact to solve a problem. system _________________________ describes the systems objects and their relationships. system structure _________________________ describes how the system changes as its objects interact with each other. system behavior Every system has both ___________ and _________.  Designers must specify both. Every system has both structure and behavior—Designers must specify both. The UML 2 standard specifies _____ diagram types for documenting the system models. The UML 2 standard specifies 13 diagram types for documenting the system models. Each models a distinct characteristic of a system’s structure or behavior—six diagrams relate to system structure, the remaining seven to system behavior. _________________________________ model the ways in which an object changes state. An object’s state is indicated by the values of all its attributes at a given time. When an object changes state, it may behave differently in the system. State machine diagrams What are UML Activity Diagrams? They show the flow of control How are Activity Diagrams represented? Rounded Rectangles. What is a Use-Case diagram? Shows what is the outside the system (actors) and the functionality that the system must provide (use cases) What are the three phases or levels of design models? CONCEPTUAL DESIGN Choose a modelling language and generate a conceptual model to represent the business activities. LOGICAL DESIGN Schemas and keys, relational or object oriented, logical design PHYSICAL DESIGN Create the tables in the DBMS including defining domains, creating indexes, defining domains etc. Which of the following statements is false? a) Storage of data variables and arrays is temporary. b) Data is lost when a local variable "goes out of scope." c) Files are used for long-term retention of large amounts of data. d) Data maintained in files is often called transient data. d) Data maintained in files is often called transient data. File processing programs are generally implemented in Java as __________. a. Applets. b. Multithreaded programs. c. Applications. d. Interfaces. c. Applications. Which statement is false? a. The smallest data item in a computer can assume the value 0 or the value 1. b. The term "bit" is short for "byte digit." c. Java Unicode characters are composed of 2 bytes each. d. A record is typically composed of several fields. b. The term "bit" is short for "byte digit." __________ is an I/O performance enhancement technique. a. Buffering. b. Piping. c. Pushback. d. Transaction processing. a. Buffering. __________ are synchronized communication channels between threads. a. Files. b. Buffers. c. Interfaces. d. Pipes. d. Pipes. How do methods setIn, setOut and setErr affect the standard input, output and error streams? a. They wrap the streams around another stream. b. They toggle the buffering capability of these streams. c. They redirect the standard input, output and error streams. d. They flush these streams’ buffers. c. They redirect the standard input, output and error streams. System.out and System.err are objects of what class? a. PipedOutputStream. b. FileOutputStream.  c. PrintStream. d. BufferedOutputStream. c. PrintStream. Which of the following is not an application of a File object? a. Open or edit a file. b. Determine if a file exists. c. Determine whether a file is readable. d. Determine whether a file is writable. a. Open or edit a file. To insert a in a string literal you must use __________. a. //. b. /. c. . d. ". c. . Relative paths start from which directory? a. The directory in which the application began executing. b. The root directory. c. The directory in which the Java interpreter is installed. d. None of the above. a. The directory in which the application began executing. Adding the services of one stream to another is known as; a. chaining. b. wrapping. c. adding. d. sequencing. b. wrapping. Which statement regarding Java files is false? a. Java imposes no structure on a file. b. Notions like "record" do not exist in Java files. c. The programmer must structure files to meet the requirements of applications. d. Records in a Java sequential file are stored in order by record key. d. Records in a Java sequential file are stored in order by record key. When displayed, a JFileChooser dialog does not allow the user to interact with any other program window until the JFileChooser dialog is closed. Dialogs that behave in this fashion are called __________ dialogs. a. Synchronized. b. Modal. c. Median. d. Choice. b. Modal. What interface allows objects to be converted to a series of bytes? a. Synchronized. b. Output. c. Serializable. d. Permanent. c. Serializable. Instance variables that are not to be output with that object are declared using which keyword? a. private. b. temporary. c. transient. d. ignore. c. transient. RandomAccessFile method __________ repositions the file-position pointer to any position in the file. a. seek . b. search. c. serve. d. set. a. seek . What happens when an end-of-file marker is reached? a. Nothing occurs. b. An end-of-file character is read by the program. c. The program crashes. d. An EOFException is thrown. d. An EOFException is thrown. The file-position pointer; a. always points to the beginning of the file. b. always points to the end of the file. c. points to the next byte in the file to be read or written to. d. is a reference to a File object. c. points to the next byte in the file to be read or written to. When a file is opened, the file-position pointer; a. is undefined. b. points to the beginning of the file. c. points to the end of the file. d. is positioned where it was when the file was closed. b. points to the beginning of the file. Which statement is false? a. Updating only a small portion of a sequential-access file is a relatively expensive operation. b. Updating a large portion of a sequential-access file is a relatively efficient operation. c. Updating a sequential-access file typically involves copying the file. d. Updating only a small portion of a sequential-access file is a relatively efficient operation. d. Updating only a small portion of a sequential-access file is a relatively efficient operation. Which statement is true? a. Sequential-access files are appropriate for "instant-access" applications. b. Transaction-processing systems are good examples of "instant-access" applications. c. Data cannot be inserted in a random-access file without destroying other data in the file. d. Airline reservation systems, point-of-sale systems, and automated teller machines are best implemented as sequential-access applications. b. Transaction-processing systems are good examples of "instant-access" applications. Random-access files are sometimes called; a. direct-access files. b. sequential-access files. c. instant-access files. d. None of the above. a. direct-access files. When a RandomAccessFile stream is associated with a file, data is read or written beginning at the location in the file specified by the __________. a. File-location pointer. b. Read/write pointer. c. File-position pointer. d. Transaction pointer. c. File-position pointer. Which statement is false? a. Swing components display null byte characters as rectangles. b. The file open mode for a RandomAccessFile can be "r" to open the file for reading. c. The file open mode for a RandomAccessFile can be "w" to open the file for writing. d. The file open mode for a RandomAccessFile can be "rw" to open the file for reading and writing. c. The file open mode for a RandomAccessFile can be "w" to open the file for writing. True/False:  To save data permanently within a Java program, or to retrieve that data later, you must use at least one stream. True What is a stream? A stream is an object that takes information from one source and sends it to another. The name is inspired by streams that take fish, boats, inner tube riders, and industrial pollutants from one place to another. Streams connect a diverse variety of sources, including computer programs, hard drives, Internet servers, computer memory, and CD-ROMs. Because all these things use streams, once you learn how to work with one kind of data, you will be able to work with others in the same manner. What are the 2 kinds of streams? * Input streams, which read data from a source * Output streams, which write data to a source True/False:  All input and output streams are made up of bytes, individual integers with values ranging from 0 to 255. True All input and output streams are made up of bytes, individual integers with values ranging from 0 to 255. You can use this format to represent data, such as executable programs, word-processing documents, and MP3 music files, but those are only a small sampling of what bytes can represent. A byte stream is used to read and write this kind of data. Java classes are stored as bytes in a form called _____________________. bytecode The Java interpreter runs bytecode, which doesn't actually have to be produced by the Java language. It can run compiled bytecode produced by other languages, including NetRexx and JPython. You will also hear the Java interpreter referred to as the "bytecode interpreter." Whether you work with a stream of bytes, characters, or other kinds of information, the overall process is the same.  What are these 3 steps in the process? 1. You create a stream object associated with the data. 2. You call methods of the stream to either put information in the stream or take information out of it. 3. You close the stream by calling the object's close() method. True/False:  In Java, files are represented by the File class, which also is part of the java.lang package. False In Java, files are represented by the File class, which also is part of the java.io package. Files can be read from hard drives, floppy drives, CD-ROMs, and other storage devices. What abstract data type is the ancestor of all streams that input byte-oriented data? a.    InputStream  b.    ByteInputStream c.    BufferedByteInputStream d.    ByteReader a.    InputStream Which of the following opens the file "myData.stuff" for Input? a. FileInputStream fis = new FileInputStream( "myData.stuff", true) b. FileInputStream fis = new FileInputStream( "myData.stuff") c. DataInputStream dis = new DataInputStream( "myData.stuff" ) d. FileInputStream fis = new FileInputStream( new BufferedInputStream( "myData.stuff") ) b. FileInputStream fis = new FileInputStream( "myData.stuff") What is the DataInputStream method that reads an int value? a.    ReadInt() b.    ReadInteger() c.    readInt() d.    read() c.    readInt() Say that a file was created using many calls to DataOutputStream.writeInt(). Is it possible to read that file with DataInputStream.readDouble()? a.    No---the hardware will not let this happen. b.    No---the compiler will not let this happen. c.    Yes--although the results almost certainly will be wrong. d.    Yes--nothing wrong in doing that. c.    Yes--although the results almost certainly will be wrong. In practice, is it always possible to know how to interpret the bytes in a given file? a.    No---because byte patterns can mean almost anything and often documentation is poor or missing. b.    No---files from one type of computer can't be read by any other type. c.    Yes--data and file formats are the same with all programs on all computers. d.    Yes--all you need to do is try all possible interpretations until you find the one that works. a.    No---because byte patterns can mean almost anything and often documentation is poor or missing. Is input and output with binary files slower or faster than with character-oriented files? a.    Slower---because primitive data take more memory than characters. b.    Slower---because primitive data must be translated into characters when doing IO. c.    Faster---because binary data does not use a buffer. d.    Faster---because binary data is more compact and does not need translation. a.    Slower---because primitive data take more memory than characters. What data type does DataInputStream.readUnsignedByte() evaluate to? a.    byte b.    Byte c.    int d.    null c.    int What happens when DataInputStream.readLong() reaches the end of the input file? a.    Control automatically leaves the program. b.    A null value is returned. c.    The program crashes. d.    An EOFException is thrown. d.    An EOFException is thrown. It it possible to make a copy of a file without knowing the format of the data it contains? a.    No---you must know what each byte means in order to copy it to a file. b.    No---files must have a header that describes the rest of the bytes. c.    Yes--any file can be copied as long as all the data is the same type. d.    Yes--a byte-by-byte copy works for all data. d.    Yes--a byte-by-byte copy works for all data. What happens when the constructor for FileInputStream fails to open a file for reading? a.    It returns null. b.    It throws a FileNotFoundException. c.    It throws a DataFormatException. d.    It throws a ArrayIndexOutOfBoundsException. b.    It throws a FileNotFoundException. What is the best definition of a binary file? a.    A file who's bytes contain only ones and zeros. b.    A file who's bytes might contain any pattern of ones and zeros. c.    A file that only contains bytes. d.    A file that does not contain any bytes that represent characters. b.    A file who's bytes might contain any pattern of ones and zeros. How many patterns can be formed from 8 bits? a.    8 b.    16 c.    64 d.    256 == 28 d.    256 == 28 What abstract data type is the ancestor of all streams that output byte-oriented data? a.    OutputStream  b.    ByteOutputStream c.    BinaryOutputStream  d.    ByteStream a.    OutputStream Which of the following opens the file "myData.stuff" for output first deleting any file with that name? a.    FileOutputStream fos = new FileOutputStream( "myData.stuff", true ) b.    FileOutputStream fos = new FileOutputStream( "myData.stuff") c.    DataOutputStream dos = new DataOutputStream( "myData.stuff" ) d.    FileOutputStream fos = new FileOutputStream( new BufferedOutputStream( "myData.stuff") ) b.    FileOutputStream fos = new FileOutputStream( "myData.stuff") What is an advantage of using a DataOutputStream? a.    A DataOutputStream has convenient methods for output of primitive data types. b.    A DataOutputStream translates primitive data into characters. c.    A DataOutputStream uses the particular data format of the computer it is running on. d.    A DataOutputStream need not be used with other streams. a.    A DataOutputStream has convenient methods for output of primitive data types. What is the name of the printed output of a program that shows the byte-by-byte contents of a binary file? a.    Charmed Display b.    Hex Dump c.    Binary Refuse d.    Pattern Listing b.    Hex Dump A program writes ten int values to a new file. How many bytes long is the file? a.    Depends on the size of the values in the ints. b.    10 c.    20 d.    40 d.    40 What is the DataOutputStream method that writes double precision floating point values to a stream? a.    write() b.    writeDouble() c.    writeFloat() d.    writeBytes() b.    writeDouble() One of the bit patterns that an int variable might hold, as it might be written on paper or on a blackboard, is: 00000000 01010101 11111111 00001111 Which eight bits are the low-order byte? a.    00000000  b.    01010101 c.    11111111  d.    00001111 d.    00001111 What  DataOutputStream method reports the number of bytes written to a stream so far? a.    size() b.    length() c.    written() d.    flush() a.    size() The action of reading data from a file is known as _____________. a) File Output b) File Input c) Saving d) File I/O b) File Input The two types of file access operations are _________________. a) Public access and private access b) Protected access and private access c) Read access and write access d) Public access and protected access c) Read access and write access Assume we wish to represent a file named, “hello” with the symbol, x.  How would we do it? a) Directory x = new Directory(“hello”); b) File x = new File(“hello”); c) Directory hello = new File(x); d) File hello = new File(x); b) File x = new File(“hello”); Using the File class, how would you open a file named “Jenny.data” that is stored in the directory, “C:/mystuff”? a) File x = new File(“mystuff”,”Jenny.data”); b) File x = new File(“C:/mystuff/Jenny.data”); c) File x = new File(“Jenny.data”, “C:/mystuff”); d) File x = new File(“C:/mystuff”, “Jenny.data”); d) File x = new File(“C:/mystuff”, “Jenny.data”); What is the difference in path name specification between the UNIX and Windows operating systems? a) There are no .exe files in UNIX but there are .exe files in Windows b) UNIX allows for spaces in file and directory names while Windows does not. c) UNIX separates directories from subdirectories with forward slashes while Windows separates directories with backslashes. d) There is no difference c) UNIX separates directories from subdirectories with forward slashes while Windows separates directories with backslashes. Assume you are in a directory;   C:/a/b/c/d/ and wish to execute the file; C:/a/yes.data  Which of the following is an invalid method to perform the execution? a) Shell>>cd ..     Shell>>cd ..     Shell>>cd ..     Shell>>yes.data b) Shell>>../../../yes.data c) Shell>>/a/yes.data d) Shell>>yes.data d) Shell>>yes.data Assume you want to list the contents of the directory, “C:/myDocs”.  How would you do this? a) System.out.println(File.list(“myDocs”)); b) System.out.println(dir.list()); c) File dir = new File(“C:/myDocs”); System.out.println(dir.list()); d) File dir = new File(“C:/myDocs/*.*”); System.out.println(dir); c) File dir = new File(“C:/myDocs”);System.out.println(dir.list()); Consider the following block of code.  What is the output?  (Assume all files in this operating system have extensions.) File file = new File(“C:/papers/stuff”); if (file.isFile()){   System.out.println(“I am a file”); } else{   System.out.println(“I am a directory”); } System.out.println(“I am done”);   a) I am a file     I am done b) I am a directory     I am done c) I am done d) I am a file b) I am a directory        I am done Assume you open a Web browser and right-click a picture on any Website.  You then click on save target as…  Notice the new window that pops up.  Which Java Swing object would allow a programmer to create such a pop up window? a) JFile b) FileChooser c) FileTextBox d) JFileChooser d) JFileChooser Which method of the FileChooser class should you use to filter files from a list of files? a) accept b) filter c) parse d) None of the above a) accept In the file “hello.java”, “java” is the ___________ of the file name. a) type b) class c) extension d) header c) extension A(n) _________ is a sequence of data items, usually 8-bit bytes. a) destination b) output c) stream d) input c) stream Once we have opened a file for access in a Java program, which of the following objects is needed to write to the file? a) FileInputStream b) FileOutputStream c) BufferedInputReader d) BufferedStringWriter b) FileOutputStream The operation of saving data as a block is known as ____________. a) data grouping b) blocking c) block saving d) data caching d) data caching At the end of any file access operation, input or output, what action should be taken to ensure that all data was saved to the file? a) open the file and check the contents b) close the file streams c) output the file contents d) None of the above b) close the file streams Assuming that outStream is a properly declared FileOutputStream object, what is wrong with the following code? byte[] byteArray= { (byte)’Y’, (byte)’E’,(byte)’S’}; outStream(print(byteArray); outStream.close(); a) single characters are not permitted to be cast to byte objects. b) one cannot send an entire array into the print method. c) print is not a valid method of the FileOutputStream class. d) the fileStream is not closed properly c) print is not a valid method of the FileOutputStream class. In order to print primitive data types to a file without having to convert them into bytes, one can use the _____________ class. a) DataInputStream b) DataOutputStream c) FileInputStream d) FileOutputStream b) DataOutputStream Assume you want to read the contents of a file and display to the monitor.  Which file I/O classes can we use to accomplish this? a) FileInputStream or FileOutputStream b) FileInputStream or DataInputStream c) FileOutputStream or DataOutputStream d) DataInputStream or DataOutputStream b) FileInputStream or DataInputStream What type of file format is a text editor capable of interpreting? a) human language b) machine language c) binary d) ASCII d) ASCII If you want to perform an object I/O then the class definition must include the phrase _________________. a) ObjectInputStream b) ObjectOutputStream c) implements Serializable d) throws Serializable c) implements Serializable True or false?  With object I/O, data are read and saved as objects. True True or false?  The lowest level of file I/O is implemented with the DataInputStream and DataOutputStream classes. False True or false?  To save objects to a file, the class they belong to must implement the Serializable interface. True True or false?  A File object represents a file or a directory. True True or false?  print() is a method of the DataOutputStream class. False True or false? When reading and writing objects, one cannot save a whole array at once.  One must save the array elements individually. False True or false?  Primitive type arrays can be cast from one type to another. True True or false?  The IOException exception exclusively handles the possibility of wrong typecasting in Object I/O. False True or false?  A text file is a file that must be converted into binary form in order to be compiled by the Java compiler. False True or false?  In order to ensure that all I/O operations are committed, the close() method should be called on all open streams. True True or false?  A FileStream object can only take in as an argument a File object. False True or false?  The goal of data caching is to save space in main memory. False True or false?  Typecasting chars to bytes or bytes to chars is a difficult task because of the differing bit sizes of each of the data types. False True or false?  C:JavaProjectsCh11 is a typical Windows filepath. True True or false?  The accept() method of the FileFilter interface returns a Boolean value. True True or false?  In Java, one dot (.) represents “one directory above”, while two dots (..) represents “two directories above”. False True or false?  With text I/O, data are read and saved as strings. True Which of the following classes is not  used for reading data from a file? a. FileInputStream b. Scanner c. FileReader d. None of the above d. None of the above Streams that input bytes and output bytes to files are known as: a) Bit-based streams b) Byte-based streams c) Character-based streams d) Unicode-based streams b) Byte-based streams Which of the following returns the length of a Node List? a. length() b. length c. size() d. None of the above d. None of the above Which of the following can be used to create a Document object? a. DocumentBuilderFactory b. DocumentBuilder c. SAXBuilder d. All of the above b. DocumentBuilder c. SAXBuilder Which of the following statements is true? a) JSON is more efficient than XML. b) JDOM is lightweight and is better than the traditional DOM parser of JAVA. c) An attribute in JDOM is data typed as Attribute while it is data typed as Node in the traditional DOM parser of JAVA. d) All of above are true. d) All of above are true. True/False: The list() method of the File class returns an array of File objects. False True/False: FileFilter is an interface that offers only one method called filter and the latter is used to check to see whether a given file should be filtered out. False True/False: A JSON array is delimited by opening and closing square brackets. True True/False: To get the JSONObject stored at index i of the JSONArray called itemsList, one can use the following statement: JSONObject item = itemsList.get(i); False True/False: When creating an HTML document, developers must use a set of predefined tags. True True/False:  In the case of method overloading, there must be an IS-A relationship. False Abstraction hides the ________________. a) class b) complexity b) complexity What is the difference between aggregation and composition? a) Aggregation represents strong relationship whereas composition represents weak relationship b) Aggregation represents weak relationship whereas composition represents strong relationship b) Aggregation represents weak relationship whereas composition represents strong relationship If there is private method in the class, which type of binding will there be? a) static b) dynamic a) static Abstract method can be in ________________. a) normal class b) abstract class b) abstract class True/False:  The return type can be the same in method overriding. True True/False: One of the features of object-based programming languages is inheritance. False True/False:  Runtime polymorphism can be achieved by data members. False Name should be started with lowercase letters in the case of ___________________. a) interface b) method b) method The input/output package usually used with Java is; a) java.inout b) java.io c) java.inout d) javafile b) java.io Can data flow through a given stream in both directions? a) No; a stream has one direction only, input or output. b) No; streams only work for output. c) Yes; only one stream is needed to read or write. d) Yes; but only one direction at a time. a) No; a stream has one direction only, input or output. What is the name of the abstract base class for streams dealing with character input? a) InputStream b) OutputStream c) Reader d) Writer c) Reader Is the character data used inside a Java program exactly the same format as the character data in a text file written by Java? a) No.  Internally Java uses 8-bit character data, but text files always use ASCII. b) No. Internally Java programs always use 16-bit char data; but text files are written in UTF format, which is different. c) Yes.  Java uses the same format for characters inside a program and in text files. d) Yes.  Character data has always used the same format for all computers and all files. b) No. Internally Java programs always use 16-bit char data; but text files are written in UTF format, which is different. A stream that is intended for general purpose IO, not usually character data, is called_____________. a) Reader b) Writer c) Byte Stream d) Character Stream c) Byte Stream What is a buffer? a) A section of memory used as a staging area for the input or output of data.  b) The cable that connects a dat source to the bus. c) Any stream that deals with character IO. d) A file that contains binary data. a) A section of memory used as a staging area for the input or output of data. Can a stream act as a data source for another stream? a) No.  Streams must be connected directly to physical devices. b) Yes.  Some streams can be connected together. c) Yes.  An input stream can be connected to an output stream. c) Yes.  An input stream can be connected to an output stream. What is the name of a stream that connects two running programs? a) program stream b) conduit c) pipe d) channel c) pipe What is a stream that transforms data in some way called? a) processing stream b) transformer c) UTF stream d) pipe a) processing stream What is the name of the abstract base class dealing with general purpose (non-character) input? a) InputStream b) OutputStream c) Reader d) Writer a) InputStream End-of-line comments that should be ignored by the compiler are denoted using:    a) A slash and two stars ( /** ).   b) Two forward slashes ( // ).   c) A slash and a star ( /* ).   d) Three forward slashes ( /// ). b) Two forward slashes ( // ). Which of the following does not cause a syntax error to be reported by the C++ compiler?    a) Extra blank lines.   b) Missing */ in a comment.   c) Missing ; at the end of a statement.   d) Mismatched {}. a) Extra blank lines. Which of the following is not a syntax error?   a) std::cout << 'Hello world! ';   b) std::cout << Hello world!;   c) std::cout << "Hello                                         world! "; d) std::cout << "Hello world! "; c) std::cout << "Hello                                                                                             world! "; The escape sequence for a newline is:    a) n   b) t   c) r   d) a a) n Which of the following statements would display the phrase C++ is fun?    a) std::cout << '++ is fun';   b) std::cout << "Thisis funrC++ ";   c) std::cout << C++ is fun;   d) std::cout << ""C++ is fun""; b) std::cout << "Thisis funrC++ "; Which of the following is not a valid C++ identifier?    a) m_x   b) width   c) _AAA1   d) my Value d) my Value Which is the output of the following statements?  std::cout << "Hello "; std::cout << "World";    a) Hello      World   b) World Hello   c) Hello World   d) World      Hello c) Hello World Which of the following characters is the escape character?    a) "   b) n   c) *   d) d) Which of the following code segments prints a single line containing hello there with the words separated by a single space?    a) std::cout << "hello" , " there";    b) std::cout << "hello ";      std::cout << " there";    c) std::cout << "hello";      std::cout << " there";   d) std::cout << "hello";      std::cout << "there"; c) std::cout << "hello";         std::cout << " there"; Which of the following is a variable declaration statement?    a) int total;   b) int main()   c) // first string entered by user   d) #include a) int total; A(n) ________ enables a program to read data from the user.    a) main declaration.  b) return statement.   c) std::cout.   d) std::cin. d) std::cin. The assignment operator ________ assigns the value of the expression on its right to the variable on its left.    a) ->.   b) #.   c) =.   d) <-. c) =. The std::endl stream manipulator:    a) outputs a newline.   b) outputs a newline and flushes the output buffer.   c) terminates the program.   d) flushes the output buffer. b) outputs a newline and flushes the output buffer. Which of the following statements does not overwrite a preexisting value stored in a memory location?    a) width = length;.   b) y = y + 2;.   c) number = 12;.   d) int a;. d) int a;. Associations in a class diagram that do not have navigability arrows at both ends indicate ___________________. a) no navigability b) one-way clockwise navigability c) one-way counterclockwise navigability d) bidirectional navigability d) bidirectional navigability Which of the following statements could potentially change the value of number2?    a) sum = number1 + number2;   b) std::cin >> number2;   c) number1 = number2;   d) std::cout << number2; b) std::cin >> number2; What is the value of result after the following C++ statements execute?  int a, b, c, d, result; a = 4; b = 12; c = 37; d = 51; result = d % a * c + a % b + a;    a) 119.   b) 51.   c) 127.   d) 59. a) 119. List the following operators in the order that they will be evaluated: -, *, /, +, %. Assume that if two operations have the same precedence, the one listed first will be evaluated first.    a) -, *, %, +, /.   b) +, -, /, *, % c)  *, /, %, -, +.   d) -, +, %, *, /. c)  *, /, %, -, +. Which of the following is not an arithmetic operator?   a) -   b) %   c) + d) = d) = Which of the following is not an actor of the ATM system? a) A user who views an account balance b) A user who provides requirements for building the ATM system c) A user who withdraws cash from the ATM d) A user who deposits funds into the ATM b) A user who provides requirements for building the ATM system What will be the output after the following C++ statements have been executed?  int a, b, c, d;      a = 4;      b = 12;      c = 37;      d = 51;      if ( a < b )      cout << "a < b";      if ( a > b )      cout << "a > b";       if ( d <= c )       cout << "d <= c";       if ( c != d )       cout << "c != d";     a) a > b      c != d   b) a < b     c < d     a != b   c) a < b     d <= c     c != d    d) a < b     c != d d) a < b        c != d Which of the following is never a compilation error?    a) Using a single equals sign instead of a double equals sign in the condition of an if statement.   b) Omitting the left and right parentheses for the condition of an if statement.   c) Placing a semicolon at the end of the first line of an if statement.   d) Neglecting to declare a local variable in a function before it is used. c) Placing a semicolon at the end of the first line of an if statement. Which of the following statements is false? a) Exception handling enable programmers to write robust and fault-tolerant programs.  b) Exception handling can catch but not resolve exceptions. c) Exception handling can resolve exceptions. d) All of the above are true. b) Exception handling can catch but not resolve exceptions. Each of the following is a relational or equality operator except:    a) ==   b) =!   c) >   d) <= b) =! The use case diagram models ________.    a) each software life cycle by repeating one or more stages several times via use cases.   b) each software life cycle stage in succession.   c) the interactions between implementations and testing.   d) the interactions between a system’s client and the system. d) the interactions between a system’s client and the system. Which of the following is not an actor of the ATM system?    a) A user who withdraws cash from the ATM.   b) A user who provides requirements for building the ATM system.   c) A user who deposits funds into the ATM.   d) A user who views an account balance. b) A user who provides requirements for building the ATM system. Which diagram models system structure?    a) Class diagram.   b) Activity diagram.   c) State machine diagram.   d) Sequence diagram. a) Class diagram. Which diagram is also called a collaboration diagram?    a) Activity diagram.   b) Communication diagram.   c) State machine diagram.   d) Sequence diagram. b) Communication diagram. With reference to Figure 1, what do you think is the most likely implementation of the relationship between Car and Engine? Choose only one option. a) A field, of type Car, in Engine.   b) A class called CarEngine with one field of type Car and another field of type Engine.   c) A field, of type Engine, in Car.   d) A field, of type Engine, in Car and a field, of type Car, in Engine. c) A field, of type Engine, in Car. With reference to Figure 1, which of the following statements are true? Choose all options that apply. a) A car always has the same body.   b) Some cars have spare wheels.   c) A car has one engine, and engines are not shared between cars.   d) All cars have either four or five wheels.   e) A car must have at least one driver.   f) Passengers cannot be drivers. a) A car always has the same body.   c) A car has one engine, and engines are not shared between cars.   d) All cars have either four or five wheels. Why are layers important in subsystem design? Choose all options that apply.   a) They make it easier to change the implementation.   b) They reduce the number of classes in the implementation.   c) They increase reuse.   d) They reduce complexity. a) They make it easier to change the implementation.   c) They increase reuse.   d) They reduce complexity. With reference to Figure 2, which methods correspond to the following message sends (in the order given)? Choose only one option.  tr.height();  sh.perimeter();  sq.height();  sq.perimeter();  sh.height();  tr.perimeter(); a)  3, 1, none (error), 4, none (error), 5.   b)  3, 5, none (error), 4, 3, 5.   c)  3, 1, none (error), 4, 3, 5.   d)  3, 5, none (error), 4, none (error), 5. d)  3, 5, none (error), 4, none (error), 5. With reference to Figure 2, which of the following message sends would be allowed by a compiler? Choose all options that apply. a) sh.perimeter();   b) tr.perimeter();   c) sh.height();   d) sq.height();   e) sq.perimeter();   f) tr.height(); a) sh.perimeter();   b) tr.perimeter();   e) sq.perimeter();   f) tr.height(); In a UML class diagram, how are objects distinguished from classes? Choose only one option. a) Object labels are shown in italics.   b) Class labels have a box drawn around them.   c) Object labels are underlined. c) Object labels are underlined. With reference to Figure 2, which of the following assignments would be allowed by a compiler? Choose all options that apply. a) sq = sh;   b) sh = tr;   c) tr = sq;   d) tr = sh;   e) sh = sq;   f) sq = tr; b) sh = tr;   e) sh = sq; What is a "class invariant"? Choose only one option.   a) A class whose source code is versioned and therefore cannot be changed.   b) A class whose objects have constant fields.   c) A condition that will always be true for an instance of the class. c) A condition that will always be true for an instance of the class. PizzaBase Case Study  The PizzaBase restaurant wants to automate the ordering of pizzas by customers. Each table will be fitted with a touch-sensitive screen which customers can use to browse the pizzas on offer and select their choice. Two basic types of pizza will be offered: the Do-it-Yourself will have a base with tomato sauce only and then customers can choose any number of toppings, at a fixed price per topping; the Prefab will come in several varieties, each with a fixed set of toppings. Every pizza can be ordered with a deep crust or crispy base, and three sizes are available: 6 inch, 9 inch and 12 inch. Customers will also be able to order from a fixed set of drinks, such as cola and lemonade flavours, each in large or small size. Once customers have confirmed their order, they will be shown the final price and, thereafter, the screen will display the progress of their food as it is being prepared and cooked. At the end of a meal, payment will be made in the conventional way. With reference to the PizzaBase case study, which of the following is the most likely list of attributes at the analysis stage? Choose only one option.   a) cola, base, price, size, lemonade, payment.   b) flavour, variety, payment, final, display, meal, tomato.   c) progress, variety, flavour, price, touchSensitive, size, drink.   d) base, price, variety, size, progress, flavour. d) base, price, variety, size, progress, flavour. PizzaBase Case Study  The PizzaBase restaurant wants to automate the ordering of pizzas by customers. Each table will be fitted with a touch-sensitive screen which customers can use to browse the pizzas on offer and select their choice. Two basic types of pizza will be offered: the Do-it-Yourself will have a base with tomato sauce only and then customers can choose any number of toppings, at a fixed price per topping; the Prefab will come in several varieties, each with a fixed set of toppings. Every pizza can be ordered with a deep crust or crispy base, and three sizes are available: 6 inch, 9 inch and 12 inch. Customers will also be able to order from a fixed set of drinks, such as cola and lemonade flavours, each in large or small size. Once customers have confirmed their order, they will be shown the final price and, thereafter, the screen will display the progress of their food as it is being prepared and cooked. At the end of a meal, payment will be made in the conventional way. With reference to the PizzaBase case study, which of the following is the most likely list of analysis classes? Choose only one option.   a) Payment, Order, Drink, Topping, Pizza, Order, Restaurant, Base, Sauce.   b) Customer, Table, Pizza, Topping, Drink, Restaurant, Order.   c) PizzaBase, Cola, Restaurant, Lemonade, Customer, Do-it-Yourself, Prefab, Table, Order.   d) Restaurant, Pizza, Topping, Display, Order, Payment, Touch.   e) Screen, Order, Offer, Topping, Size, Meal, Pizza, Restaurant.   f) Pizza, Customer, Cook, Table, Crust, Topping, Drink, Restaurant. b) Customer, Table, Pizza, Topping, Drink, Restaurant, Order. PizzaBase Case Study  The PizzaBase restaurant wants to automate the ordering of pizzas by customers. Each table will be fitted with a touch-sensitive screen which customers can use to browse the pizzas on offer and select their choice. Two basic types of pizza will be offered: the Do-it-Yourself will have a base with tomato sauce only and then customers can choose any number of toppings, at a fixed price per topping; the Prefab will come in several varieties, each with a fixed set of toppings. Every pizza can be ordered with a deep crust or crispy base, and three sizes are available: 6 inch, 9 inch and 12 inch. Customers will also be able to order from a fixed set of drinks, such as cola and lemonade flavours, each in large or small size. Once customers have confirmed their order, they will be shown the final price and, thereafter, the screen will display the progress of their food as it is being prepared and cooked. At the end of a meal, payment will be made in the conventional way. With reference to the PizzaBase case study, which of the following options are likely business use cases? Choose all options that apply.   a) Customer pays for meal.   b) Restaurant prepares meal.   c) Customer sees progress of food.   d) Customer chooses pizza.   e) Customer selects drink from display. a) Customer pays for meal.  b) Restaurant prepares meal.   d) Customer chooses pizza. PizzaBase Case Study  The PizzaBase restaurant wants to automate the ordering of pizzas by customers. Each table will be fitted with a touch-sensitive screen which customers can use to browse the pizzas on offer and select their choice. Two basic types of pizza will be offered: the Do-it-Yourself will have a base with tomato sauce only and then customers can choose any number of toppings, at a fixed price per topping; the Prefab will come in several varieties, each with a fixed set of toppings. Every pizza can be ordered with a deep crust or crispy base, and three sizes are available: 6 inch, 9 inch and 12 inch. Customers will also be able to order from a fixed set of drinks, such as cola and lemonade flavours, each in large or small size. Once customers have confirmed their order, they will be shown the final price and, thereafter, the screen will display the progress of their food as it is being prepared and cooked. At the end of a meal, payment will be made in the conventional way. With reference to Figure 3, which diagram is the best model of Pizzas in the PizzaBase restaurant? Choose only one option. a) Diagram 1.   b) Diagram 2.   c) Diagram 3. b) Diagram 2. Currently, what is the most common type of database management system? Choose only one option.   a) Network   b) Relational.   c) Object-oriented.   d) Hierarchical.   e) Indexed file. b) Relational. What are some of the advantages of Java as an implementation technology? Choose all options that apply.   a) Object-oriented purity.   b) Invented by Microsoft.   c) Network readiness.   d) Portability.   e) Scalability.   f)  Security. a) Object-oriented purity.   c) Network readiness.   d) Portability.   e) Scalability.   f)  Security. What can an object-oriented type system be used for? Choose all options that apply.   a) Improving runtime performance.   b) Preventing misuse of a class.   c) Avoiding spelling mistakes.   d) Making sure that all messages invoke a concrete method.   e) Documentation. a) Improving runtime performance.   b) Preventing misuse of a class.   c) Avoiding spelling mistakes.   d) Making sure that all messages invoke a concrete method.   e) Documentation. Why is the ability to redefine a method important in object-oriented programming? Choose all options that apply.   a) Because it allows us to add extra work to a method.   b) Because it allows us to introduce abstract methods that are redefined as concrete methods.   c) Because it allows us to provide a more accurate or faster definition in a subclass.   d) Because it allows us to disable a method in a subclass.   e) Because it allows us to change the meaning of a method. a) Because it allows us to add extra work to a method.   b) Because it allows us to introduce abstract methods that are redefined as concrete methods.   c) Because it allows us to provide a more accurate or faster definition in a subclass. Which of the following statements about multiple inheritance are true? Choose all options that apply.   a) It offers more modelling choices.   b) It makes it more difficult to write compilers and fast runtime systems.   c) It simplifies inheritance hierarchies.   d) It solves the problem of repeated inheritance. a) It offers more modelling choices.   b) It makes it more difficult to write compilers and fast runtime systems. If two customers, on opposite sides of the world, wish to purchase the last ticket available for a concert, what would be a good approach for allocating the ticket? Choose only one option.   a) Introduce an extra business rule that combines a query for ticket availability with a temporary reservation.   b) Make the customers take part in a software "race" to get the ticket.   c) Don't allow the last ticket to be sold, because that would be unfair to one of the customers. a) Introduce an extra business rule that combines a query for ticket availability with a temporary reservation. With reference to Figure 4, which of the following statements are true? Choose all options that apply. a) X3 can interact with the system using UC4.   b) X1 can interact with the system using UC1 and UC4.   c) X3 and X1 are different kinds of X2.   d) UC3 is an abstract use case with no steps of its own. All four; a) X3 can interact with the system using UC4.   b) X1 can interact with the system using UC1 and UC4.   c) X3 and X1 are different kinds of X2.   d) UC3 is an abstract use case with no steps of its own. With reference to Figure 4, which of the following statements are true? Choose all options that apply. a) UC5 is a compulsory part of UC4.   b) UC4 is an optional part of UC5.   c) UC1 is unused.   d) UC2 is an optional part of UC4.   e) UC4 is a compulsory part of UC2. a) UC5 is a compulsory part of UC4.   d) UC2 is an optional part of UC4. With reference to Figure 4, what are X1, X2 and X3? Choose only one option. a) Roles.   b) Prima donnas.   c) Actors.   d) Sticks. c) Actors. What is meant by the term "design by fear"? Choose only one option.   a) Design is scary.   b) You cannot know when to trust the code.   c) You design a system too quickly because of time pressures. b) You cannot know when to trust the code. With reference to Figure 5, what do Diagrams 1 and 2 illustrate? Choose only one option. a) 1: An aggregation, 2: A composition.   b) 1: An attribute, 2: An aggregation.   c) 1: An aggregation, 2: An attribute.   d) 1: An attribute, 2: A composition.   e) 1: A composition, 2: An attribute. d) 1: An attribute, 2: A composition. With reference to Figure 5, what is the difference between the two diagrams? Choose only one option. a) In Diagram 1, Color is public but in Diagram 2 Color is private.   b) Diagram 2 indicates that the car's Color can be removed and replaced.   c) Diagram 1 shows an abstract class and Diagram 2 shows a concrete class.   d) None, they mean the same thing. d) None, they mean the same thing. What is meant by "object identity"? Choose only one option.   a) Two objects are identical if their attributes have the same value.  b) Every object's class has a unique serial number.  c) All objects are the same as each other.   d) Every object has a unique identity that distinguishes it from all other objects. d) Every object has a unique identity that distinguishes it from all other objects. Which of the following UML artifacts are used to show the distribution of processes, artifacts and model elements in a system? Choose only one option.   a) Interaction diagrams.   b) Sequence diagrams.   c) Deployment diagrams.   d) Communication diagrams.   e) State machine diagrams.   f) Class Diagrams.   g) Glossaries. c) Deployment diagrams. Which of the following terms best describes an object that is made up of other objects? Choose only one option.   a) Generalization.   b) Inheritance.   c) Association.   d) Aggregation.   e) Specialization. d) Aggregation. With reference to Figure 6, what kind of objects are A, B and C? Choose only one option. a) A is an entity, B is a controller, C is a boundary.   b) A is a boundary, B is an entity, C is a controller.   c) A is an entity, B is a boundary, C is a controller.   d) A is a controller, B is an entity, C is a boundary.   e) A is a boundary, B is a controller, C is an entity.   f) A is a controller, B is a boundary, C is an entity. d) A is a controller, B is an entity, C is a boundary. With reference to Figure 6, which kind of icon would you use to represent a business object containing useful information? Choose only one option. a) A b) B c) C b) B