Comp150 Final Study Guid
How do you start a multi-line comment?
/*
How do you start a single line comment?
//
The result of 3 / 2 is _________________ .
1
The result of 9 % 2 is _________________ .
1
Which of the following is NOT true about assigning values?
A constant's value can be reassigned no more than three times in a program.
Why is it a good idea to check that c is less than arrayName[r].length before attempting to access arrayName[r][c]?
All of the above are true: Accessing columns that do not exist will result in ArrayIndexOutofBoundsException at run time. Rows might have a different number of columns. The column number must be within the range of 0 to arrayName[i].length - 1.
Which of the following questions should you ask to verify a clean program?
All of these are required tests: Does the program deal appropriately with invalid input? Does the program produce correct results with a set of known inputs? Does the program produce correct results if the sentinel value is the first and only input?
What happens if you try to access an array element using a negative index or an index greater than or equal to the number of elements in the array?
ArrayIndexOutOfBoundsException
How do you declare an ArrayList object named books which references a collection of Book objects?
ArrayList<Book> books;
Identify if there are any operators lower in operator precedence than conditional operators. (lower precedence operations happen later)
Assignment operators are lower.
Unicode is a world standard to represent _________________
Character data Character characters Character Data Characters character data character
An abstract method _________________
Does not have a body
Comments slow down the runtime of the program
False Comments make compilation time infinitesimally longer (the compiler skips over them, and it takes some tiny amount of time to do so), and they are completely left out of the .class outputs, which are the files used when running. Thus, comments do not affect the runtime of the program at all.
Declaration creates and assigns value to a variable.
False Declaration only creates the variable. Assignment assigns value to it. The first assignment to a variable is called an initialization. Identically, the first assignment to a variable is said to initialize the variable.
True or False? tax Rate is a valid identifier.
False Identifiers cannot contain spaces. Spaces are neither java letters nor digits. taxRate would be valid, but tax Rate is not.
True or False? 2008taxRate is a valid identifier.
False Identifiers must start with a java letter.
The body of a while loop is executed until the loop condition becomes _____
FALSE false False
&& and || have the same level of precedence.
False
= is the equality operator; it compares two values and returns true if they are equal and false otherwise.
False
An else block is mandatory after an if
False
In an if statement, curly braces around the true block are always mandatory
False
Primitive variables can be set to null.
False
The conditional operator ?: has lower precedence that the = operator
False
The wrapper class for char is Char
False
Three-dimentional arrays are not allowed in Java
False
True or False: A java class can extend multiple other classes.
False
True or False: Abstract classes can be instantiated without being extended.
False
True or False? A class must implement at least one interface.
False
True or False? A constructor can be declared abstract.
False
True or False? A method cannot return a two-dimensional array.
False
True or False? Abstract methods can be called.
False
True or False? Abstract methods can be private.
False
True or False? Abstract methods can be static.
False
True or False? An abstract class cannot be extended.
False
True or False? An interface can contain a constructor.
False
True or False? An interface can contain instance variables.
False
True or False? If a class has an abstract method, then that class must be an interface.
False
True or False? In a given class, there can be only one constructor
False
True or False? In a two-dimensional array, the number of elements in each subarray must be the same for every subarray.
False
True or False? In an array we can have a mix of integers and Strings.
False
True or False? In the += shortcut operator, there is a space between + and =.
False
True or False? It is always necessary to use the keyword this to access instance data within an instance method.
False
True or False? Methods cannot return arrays.
False
True or False? Mutator methods generally take no arguments.
False
True or False? Only constructors can be overloaded.
False
True or False? Private instance data can be accessed from methods of other classes.
False
True or False? String is in the java.string package.
False
True or False? The base for hexadecimal numbers is 15.
False
True or False? The body of a while loop always executes at least once.
False
True or False? To compare two arrays for equality, you call the equals method with the first array and pass the second array as the argument.
False
True or False? We can store primitive data types in an ArrayList object.
False
True or False? We cannot combine the declaration and instantiation of a multidimensional array.
False
True or False? We cannot combine the declaration and instantiation of an array.
False
Using a null object reference to call a method will not generate an error.
False
When a multidimensional array is instantiated, elements of arrays with primitive numeric types are initialized to null.
False
When comparing objects for equality, we typically use the == operator
False
When using an if/else if structure, it is mandatory to have an else block
False
When writing code, you can include two forward slashes for a comment and then later replace them with back slashes to uncomment.
False
True or False? * is a unary operator.
False * is binary. un means 1, unary operators have 1 input bi means 2. binary operators have 2 inputs * multiplies 2 numbers, so it has 2 input
Inside an if statement, statements inside the true block must be indented, otherwise the code will not compile
False All indentation is for readability in Java. This does not mean it is optional ;) Some other languages (like Python) use indentation for syntax purposes, but Java does not.
If you log into AWSEducate from a different computer, all of your files in Cloud9 will be gone and you'll need to start over.
False All of the files are on one of Amazon's servers; you can sign in from a different computer, and you'll still access the same server, so all of your files will still be there.
The files that you write in Cloud9 are saved on your computer.
False Cloud9 is an IDE for development on Amazon's servers. When you work in Cloud9, you edit these files using your web browser. The files, as well as program executions, are all on an Amazon server in a warehouse somewhere.
True or False? Every class has a default constructor (i.e. one which takes no arguments).
False If a class doesn't contain any constructors, then the default constructor is inherited from Object, but if it does define a constructor but doesn't define a default constructor then it does not have a default constructor.
When comparing two floating point numbers for equality, it is always safe to use the == operator
False Small inaccuracies are inherent in floating point operations. Generally, checking two floating point numbers for "equality" really means checking if they are close enough together to be effectively equal in context.
Strings are neither primitives nor objects.
False Strings are objects.
A variable that is declared inside the true (or false) block of an if statement is still in scope after we exit that block.
False We didn't cover this in the reading, but just like the for loop, variables declared in one block cannot be accessed outside of that block.
True or False? char is a valid identifier.
False char is a keyword, used to declare data of type char. identifiers cannot be keywords.
If you specify that a data item is a double, then the compiler will allocate 16 bytes of memory to store this item
False doubles take up 8 bytes of memory.
________ methods allow the clients get the value of private data.
Getter accessor GETTER getter ACCESSOR Accessor
IDE stands for ___________.
Integrated Development Environment integrated development environment
The data type of the return value of the toString method is generally a
String
Can we store primitive data types in an ArrayList? Justify your answer.
Technically, no. ArrayLists can only store objects. Functionally, yes. We just use the wrapper classes to store the primitive data in object form.
In addition to modifying instance, what is sometimes the other function of mutator methods?
Mutator methods also validate inputs, or enforce constraints on the data, where applicable.
Identify the two possible errors that Java would generate if you attempt to call a method using an object reference whose value is null.
NullPointerException NullReferenceException
If an if statement's body is a single statement, it does not need curly braces. Many developers add these curly braces anyway, making a single statement into a block consisting of that single statement. Theorize about why they do this.
Often extra braces will improve readability.
What can the Scanner class be used for?
The Scanner class can be used for many purposes; it is primarily used for reading input streams (user-typed input, input files, ...).
Student is an abstract class, you defined a reference variable as: Student student;
The Student class cannot construct objects directly, because it is abstract. A concrete class which extends Student will need to be created, and this class could be used to construct objects, and thereby initialize the variable.
You have a char variable whose value will be one of 5 values, 'a' 'b' 'c' 'd' or 'e'. You want to print a different message for possible value. What Java constructs could you use to do this?
The best answer is to use a switch. An if - else if - ... - else sequence would do the trick too, but the switch is simpler where it works (i.e. where the determining data in selection has a value which falls into a small number of distinct values).
List the eight primitive data types in Java, and explain why they are called primitive.
The eight primitive data types are as follows: byte int long double short float char boolean They are called primitive because they are a characteristic of the core Java language. They are called primitives because they are the basic data types out of which more complex data structures are built.
What will result if you have an if statement with two else statements?
The dangling else will generate a compiler error 'else' without 'if'.
How do you instantiate an object from an abstract class?
You cannot instantiate an object from an abstract class
Several classes implement an interface, but all of them implement the same method using the same code. How could you avoid this repetition of the same code in several different classes?
You could do one of these: Add a default implementation to the interface. Create an abstract class which implements the interface. This abstract class could implement the common method, and leave the remaining methods abstract.
A method of a class can access
The instance variables of accessible instances, its arguments, and the local variables that the method defines
What is operator precedence?
a set of rules to determine the order in which the operations should be performed
A conditional operator evaluates a condition and returns one of two values to the expression based on the value of the condition.
True
An abstract class is a class can contain declarations for methods that are not implemented.
True
An object reference (a variable referencing an object from some class) can refer to any object of its class.
True
Cloud9 is an IDE.
True
Given two boolean variables a and b, are the following expressions equivalent? !( !a && !b) a || b
True
In else if, there is a space between else and if
True
Inside the block of a switch statement, the break statements are optional
True
The 4 relational operators, >, >=, <, <= are binary operators.
True
The DecimalFormat can be used to format a number by specifying a number of digits after the decimal point
True
The conditional operator ?: can be used in expressions
True
The hasNext method in the Scanner class returns true if the input has another token, and false otherwise.
True
The instance variables of a class hold the data for each object of that class.
True
True or False: The last element in an array always has an index of 1 less than the number of elements.
True
True or False? A Java interface can extend multiple other interfaces.
True
True or False? A class can implement more than one interface.
True
True or False? A double is more precise than a float.
True
True or False? A method of a class can call other methods of that same class.
True
True or False? A single bit can store one value, either a 0 or a 1.
True
True or False? A while loop can be nested inside a for loop and vice-versa.
True
True or False? Abstract methods can be overridden.
True
True or False? All instances of all classes are instances of the Object class.
True
True or False? All the methods of the Math class are static.
True
True or False? An interface can contain abstract methods.
True
True or False? Binary numbers are composed of 0s and 1s.
True
True or False? By convention, class names start with a capital letter.
True
True or False? By convention, method names, instance variables and object names start with a lower case letter.
True
True or False? Curly braces around the loop body are optional if the loop body consists of only one statement.
True
True or False? If a class has an abstract method, then that class must be abstract.
True
True or False? If a variable tracks the number of class instances that have been constructed, it should be static.
True
True or False? In Math.abs( -5 ), abs is a static method.
True
True or False? It is possible to create user-defined classes in Java.
True
True or False? It is possible to have an array of objects.
True
True or False? Java is an object-oriented language.
True
True or False? Mutator methods are generally void methods.
True
True or False? The body of a do/while loop always executes at least once.
True
True or False? The body of a method must be surrounded by curly braces.
True
True or False? The extends keyword allows a subclass to inherit from its superclass.
True
True or False? The loop condition can be a complex condition involving several operators.
True
True or False? The loop condition is a boolean expression.
True
True or False? To process all the elements of a two-dimensional array, we can use a nested loop.
True
True or False? To process all the elements of an array, we could use a loop.
True
True or False? We can instantiate a two-dimensional array by assigning values when the array is declared.
True
True or False? We can instantiate an array by assigning values when the array is declared.
True
True or False? We can pass a two-dimensional array parameter to a method.
True
True or False? When declaring a two-dimensional array, we use two sets of square brackets.
True
True or False? When declaring an array, we use a set of square brackets.
True
True or False? for loops can be nested.
True
True or False? helloWorld is a valid identifier.
True
True or False? int9 is a valid identifier.
True
True or False? Interfaces can contain methods that are not abstract.
True Interfaces can contain concrete methods, but they must be static. Instance methods, must be abstract.
True or False? chara is a valid identifier.
True This is a valid identifier. While it contains the keyword char, it is not a keyword in its entirety, so it is fine.
True or False? Java is a high-level language.
True or False? Java is a high-level language.
An instance method (i.e. a non-static method) can reference _____________________.
all of the above: instance variables class variables class methods
In the following statement, which of the following can be true? for ( Auto current : autos )
autos is an ArrayList
An ArrayList object called books referencing a collection of Book objects has already been declared; how do you instantiate it using the ArrayList default constructor?
books = new ArrayList<Book>( );
Which one of these is not a primitive data type? _________________ .
bool
The data type of the return value of the equals method is generally a
boolean
The relational operators cannot be used with _____________.
boolean expressions or with object references
In the context of a switch statement, what is the purpose of break statements?
break statements are used in switches to stop the execution of the switch after the case for the input value has been reached.
Tha Java compiler converts Java source code into _________
bytecode Byte Codes byte code byte codes Bytecode ByteCode Byte Code
Putting a semicolon after the loop condition of a while loop will most likely result in an _____ loop
endless infinite
The _____________ enables looping through an array or ArrayList object without using a counter and without using the get method to access each object.
enhanced for loop for-each loop
== is the _________
equality operator
If it is well-written to do what it should do, then the __________ method returns true if the data in the parameter object matches the data in the object for which the method was called.
equals
What is the responsibility of equals method?
equals methods generally exist to compare two objects for equality. They must be defined in any user-created class, or the default object equals method will be called, which simply checks if the two objects have the same address.
Inside the curly braces we define the data of the class, called its ___________, and the methods.
fields or attributes
The Java keyword for a constant is _________________
final
The two floating point data types are
float double
You want to compare two floating point numbers for equality. Explain why, in some contexts, you may want to instead check if they are very close to each other (within some small margin of error).
floating point data types (float, double) accrue small rounding errors through arithmetic operations. Two floating point numbers which should be equal but whose values were calculated using different operations might not have exactly equal values.
The following header is used to access an array with index i in the loop body. When the loop is run, a runtime exception (index out of bounds) occurs. Which of the following options fixes the issue? for ( int i = 0; i <= arrayName.length; i++ ) { ... }
for ( int i = 0; i < arrayName.length; i++ )
To access the number of elements in an array named grades, we use ________________.
grades.length
To access the number of subarrays in a two-dimensional array named grades, we use _________________.
grades.length
To access the element at index i of an array named grades, we use _________________.
grades[ i ]
To access the number of elements in the subarray at index i of a two-dimensional array named grades, we use _________________.
grades[ i ].length
To access the element at index j of the subarray at index iof a two-dimensional array named grades, we use _________________.
grades[ i ][ j ]
Rewrite one (and only one) statement equivalent to: int age; age = 32;
int age = 32;
Each execution of the loop body is called an _____________ of the loop.
iteration Iteration
Classes from ________ do not need to be imported.
java.lang
In what package is the class Math?
java.lang
The ArrayList class belongs to the package _________________ .
java.util
The name of the Java compiler is _________________ .
javac
Which of the following statements about array length is true?
length functions as an instance variable
Java identifiers must start with a _______ and may contain any combination of letters and digits, but no spaces
letter Java letter java letter
Class operations, i.e. sequences of statements with a name, appear in the class body and are called _____
methods
If an array has n elements, then the last index is ______.
n - 1
The loop continuation condition is the ___________ of the loop termination condition.
negation opposite
Attributes and methods declared with the ________ keyword do are class-specific, not instance-specific
static
Class methods are accessible through a class, and don't need to be accessed through instances of the class. They have the keyword ______ before the return type.
static
Why are calls to the static methods, done with the dot operator with the class name rather than an object reference?
static methods and attributes are class-specific, not object-specific. They do not require an instance to perform (unless one is passed in as an argument), and do not require data from on or mutate an instance (again, unless once is an argument).
Which of the following should not be contained in a submitted zip file
the compiled .class files
When computing the maximum value in an array of integers by looping through and storing the maximum value encountered so far, you should initialize the maximum value to _________________.
the first element in the array
When you use a while loop to compute the average of several values, what variables do you need to keep track of in addition to holding the value being processed?
the sum of the values and how many values have been processed
The keyword _______ refers to the object from which an instance method has been called.
this
What does the toString method typically return?
toString typically returns a String value representing the object's type and data in a human-readable form.
A Scanner object divides its input into sequences of characters called
tokens
How do we compare the value of two String objects in Java?
using the equals method
Primitives are passed by ________
value
Explain the difference between value returning methods and void methods
value returning methods "result in" or "return" or "spit out" a value, whereas void methods do not. calls to value returning methods are therefore expressions, whereas calls to void methods are not expressions.
Assume we have a situation where the number of inputs cannot possibly be determined until run time. The Java feature that we would use to specify that the method accept a variable number of arguments is called __________.
varargs
If we want to store primitive data types in an ArrayList object, then we should use ___________classes.
wrapper Wrapper
Before performing a division, it is a good idea to use an if statement to test if the value of the denominator is _________________
zero 0
VM stands for _________________ .
Java Virtual Machine
What kind of loop could be used to print every element of an array, in order?
any of these: for loop do-while loop while loop
User-defined words in Java _________________.
are used as identifiers
In the method header public static void main( String [ ] args )
args is an array of Strings
A two-dimensional array is an array of _________________.
arrays
If you want to execute a loop body at least once, what type of loop would you use?
do/while loop
String literals are surrounded by _____ quotes
double
!( a > 38 && b <= 67 ) is equivalent to _________________ .
!( a > 38 ) || !( b <= 67 )
a, b, and c are booleans. a is true, b is true, and c is false. Evaluate each of the following as true or false.
!a evaluates to false a && b evaluates to true a && c evaluates to false a || c evaluates to true !( a || b) evaluates to false !a || b evaluates to true !( !( a && c ) ) evaluates to false a && !( b || c ) evaluates to false
How do you end a multi-line comment?
*/
The result of (double) ( 3 / 2 ) is _________________ .
1.0
The result of (double) 3 / 2 is _________________ .
1.5
The result of 3.0 / 2 is _________________ .
1.5
How many times will a loop with the for loop header for( i = 5; i < 15; i++ ) iterate?
10
The hexadecimal number 8C is equivalent to this binary number.
10001100
What is the output of the following code? int age = 34; if (age > 33) System.out.print( 1 ); System.out.println( 2 );
12 Note: the first print is "print", not "println", so it does not have a new line at the end.
The hexadecimal number C1 is equivalent to this decimal number.
193
Assuming the for loop header for( i = 0; i < 20; i++ ), what will be value of i after we exit the loop?
20
If you have an if/else if/else code sequence with 4 blocks, what is the minimal number of input values that you should test your code with?
4
The decimal value of the Unicode character A is _________________ .
65
Assuming the for loop header for( i = 0; i <= 7; i++ ), what will be value of i after we exit the loop?
8
A byte contains _____ bits
8 Eight EIGHT eight
When a loop condition is x >= 90, what values would you use to test your loop?
89, 90, and 91
The binary number 1010 is equivalent to this hexadecimal number.
A
What is the relationship between an object and a class?
A class describes a generic template for creating, or instantiating, objects.
What is a flag variable?
A flag variable is generally a boolean used to track a loop condition for calculation or termination purposes.
A special value that the user enters to signal the end of the input is called _________________ .
A sentinel value
What are expressions and statements? How are they different?
A statement can hold expressions. For example, int x = y + 5 is a statement that holds the expression y + 5. The main difference is that in a statement the result of your expression gets assigned to the variable. His - Expressions have a value or output something, where statements carry out a task or do something. Whenever an expression appears, it is as part of a statement.
What is an overloaded method?
An overloaded method is a collection of methods defined with the same identifier but with different arguments. They allow "one method" to work with several different argument configurations.
Assuming the class B inherits from class A, then
Any instance of class B is an instance of class A
What is API and what it is used for?
Application Programming Interface A class's API is its documentation; it provides a list and description of the data and methods in a class, what they do and how to access them.
After these statements are executed String [] words = new String[10]; System.out.println( words[0].length( ) ); A NullPointerException is generated; why?
Because words[0] has not been instantiated and is therefore null. That is, the array words has been instantiated, but currently every element of words is null (any object which has not been instantiated yet is null).
You are asking users for integer inputs from 1 to 72 and gathering data on frequency of guesses. You need to count the number of occurrences of each number 1 though 72 using an array. The number 0 will not occur and thus does not need to be counted. What are the benefits and drawbacks of creating an array with 73 elements (indexes 0 through 72) and simply never using the 0 index and instead using the remaining indexes (1 through 72), as opposed to making one with 72 elements (indexed 0 through 71) and using all of the indices (0 through 71).
Benefit: Indexing the array is easier; the tracker for the number 1 is at index 1 instead of index 0, so counting an occurrence does not require a subtraction. Drawback: Your array has 1 extra (unused) element, so that much space (4 bytes for an extra integer) is reserved for the array and never used. Summary: By using the larger array to make indexing easier, you are saving a small amount of time but losing a small amount of space.
Suppose you are looking for a name of your friend Mike Jones in the telephone directory. You open the book in the middle and look at the name at the top of the left page; it starts with an L; then mark that page and look halfway between the 1st page and that page, and you keep looking applying this same strategy; what algorithm are you using?
Binary Search Binary search binary search
_____ are required for class and method definitions. They consist of 0, 1, or more statements, start with a left curly brace, and end with a right curly brace.
Blocks block Block blocks
CPU stands for _________________
Central Processing Unit central processing unit
When preparing your completed lab for submission, which should be done last?
Compressing the folder
!( a && b ) is equivalent to !a || !b is one of two of the _________________laws.
DeMorgan
A loop condition may be simplified by applying ______ laws.
DeMorgan DeMorgan's
The statements NOT( A AND B ) = ( NOT A ) OR ( NOT B ) and NOT( A OR B ) = ( NOT A ) AND ( NOT B ) are ___________.
DeMorgan's Laws
Variables need to be declared once at the beginning and then at the end of the program.
Each variable only needs to be declared once. In fact, variables cannot be declared a second time.
It is good practice to make data private, and control how it is accessed or edited by providing methods which maintain the integrity of the data. This is called ___________
Encapsulation encapsulation ENCAPSULATION
What is encapsulation, and how can it be implemented in Java? Why is encapsulation useful?
Encapsulation is the bundling of data and methods together, in such a way as to maintain the integrity of the data by limiting access to it through methods. In other words, encapsulation is a separation of a class's internal workings (the ways it stores and manages its data) with its external use (the way clients are intended to use it). Encapsulation is useful because it maintains the integrity of data and because it separates the class's use in clients from what it does "under the hood", thereby making it reasonable to change how the class goes about implementing its data storage and its public and protected methods without necessitating edits to clients which call said methods. Encapsulation can be implemented in Java with access modifiers. Use of interfaces can also contribute to ensuring correct encapsulation.
How do you compare two arrays for equality?
First, check that the two arrays have the same length; if they don't have the same length, then they aren't equal (return false). Next, compare each element of the arrays for equality using a loop. If any element from the first array doesn't equal the corresponding element in the second array (the one at the same index) then the arrays are not equal (return false). If you made it through this whole process without finding evidence that the arrays were not equal, then they must be equal (return true).
To compare two arrays equality, which of the following actions should be taken first?
First, make sure the two arrays are the same length
Decide whether it would be a good idea to initialize the maximum value to 0 when trying to find maximum values. Explain your answer.
I would not be a good idea. What if the values that you're trying to find the max of are all negative? Then your result would be 0, instead of the largest of the values. You should instead initialize your maximum to the first value being checked, and just update it whenever you encounter a larger value.
What are the characteristics of identifiers?
Identifiers can contain lower or uppercase letters, as well as numbers between 0 to 9. - start with a java letter (an alphabet letter, an underscore, or a dollar sign) - contain only java letters and digits
Defend this statement: It is not necessary to use return expression; when the data type in the method is void.
If the data type of a method is void, then the method does not return any value. return will end the function, but it is not needed to return a value.
Inheritance is useful for which of the following?
It allows related classes to be organized into levels of functionality so they can be reused.
Which of the following is true of overriding methods?
It allows you to hide features of the superclass that are not desired.
Identify the advantage of providing multiple constructors.
It gives the client a choice of ways to create an object.
Which of these is not a reason to write readable code.
It protects your job because others can't copy your code.
Explain what will happen if you don't write a constructor for a class.
It will have a default constructor, provided by the Object class.
Explain what is wrong with the following statement: int x = 120L;
Mine - The problem with this statement is the "L" after 120. Since we are declaring the variable "x" as an integer, the value can only be a number, not a letter. His- 120L is a long literal; long data is "more complex" than int data, so a long value cannot be implicitly converted to an int. 120 is small enough to be stored in an int, so the L is unnecessary; removing the L would fix this. Alternatively, x could be declared as a long instead of an int.
Polymorphism means _______.
Multiple forms or many forms
_________ methods allow clients to change, set or manipulate private data.
Mutator MUTATOR mutator Setter SETTER setter
Compare and contrast integer division and floating point division. Give an example of a scenario in which using the wrong type of division can lead to errors.
My Answer: Floating point division is used when more precision is needed. They make use of decimal points, while integers do not. An example that came to mind is with paychecks. When you work less than an hour, you need floating point numbers to find your pay for that time. His Answer: Integer division "rounds down" (i.e. cuts off everything that would be after the decimal point in normal arithmetic division), where floating point division does not. Integer division outputs an integer type (byte, short, int, long), while floating point division outputs a floating point type (float, double). A common division error is using integer division to calculate the average of several integers. The average might not be an integer, so floating point division should be used, but if not casting is done then integer division will be used because the inputs are integers. Finding the average of 3 and 4 with integer division will result in the incorrect output of 3, whereas using floating point division will result in the correct output of 3.5.
OOP stands for _________________
Object-Oriented Programming object oriented programming Object-oriented programming Object Oriented Programming Object oriented programming object-oriented programming
Java classes are organized in (and can be imported from) _________________
Packages packages package Package
What is polymorphism? Provide at least 3 examples of polymorphism as it exists in Java.
Polymorphism is the capability of an entity to take on "many forms" or to have "many versions". In Java, there are several examples of polymorphism: Operators such as +, which perform different operations with different types of inputs Overloaded methods Multiple implementations of an interface. Multiple extensions of a single (abstract or concrete) class.
What is pseudocode?
Pseudocode is an English-like language used in place of a programming language. (I'm confused on this one though.) Pseudocode is structured natural language (we've seen some in structured english) to describe a process. It is often used in planning or analysis for programs and algorithms
Where does the add method of the ArrayList class add an object?
at the end of the list
One can generate random primitive data using the ___________ class
Random You might be able to find other classes to generate random data. This is the one we discussed in the lab.
Which is the correct order to see the output of a file you have edited?
Save, Compile, Run
Name 2 algorithms for sorting arrays
Selection Sort Insertion Sort Bubble Sort Merge Sort
In a for loop header, statements are separated with _______.
Semi-colons
Convert this if/else statement to one that uses the conditional operator. if ( a % 2 == 0 ) System.out.println("The number is even"); else System.out.println("The number is odd"):
System.out.println( a % 2 == 0 ? "The number is even" : "The number is odd" );
If two instances of Java.awt.Point called point1 and point2 have the same coordinates, then point1 == point2 is true.
The == operator will check if the two references are the same. To check if the two points have the same coordinates instead, their .equals method should be used.
What is the responsibility of a constructor?
The Constructor constructs an object (i.e. instantiates a member of the class). For instance, calling the Scanner constructer with "new Scanner (System.in)" creates a new Scanner object (i.e. instantiates a member of the Scanner class) which uses System.in as its input.
If you don't define the toString method, and then you print an instance, what happens?
The Object class's toString is used; it prints the class name, and then the address of the instance being printed.
Explain why you should provide new versions of the toString and equals methods from the Object class, generally.
The default toString and equals methods for the object class print out the location in memory of the object and compare the object's location to the input, respectively. This is usually not what is intended with toString and equals in most classes. toString should return a human-readable string representation of the object calling it, and equals should generally compare two objects for some sort of equality specific to that type of object (i.e. that class).
Contrast the do/while loop with the while loop.
The do-while loop runs the loop body once before checking the condition. So a do-while iterates at least once, whereas a while can iterate 0 times if the condition is false to begin with.
Compare the function of these two statements, where arrayName represents a two-dimensional array: arrayName.length arrayName[i].length
The first finds the length of the outer array, i.e. the number of 1D arrays in it (or the number of rows, if you prefer). The second finds the length of the specific subarray at index i of the outer array.
Show steps for converting the last three digits of your csuci student id to binary. (Your student ID is in decimal initially).
The last three digits of my CSUCI student ID is 130. What I usually do to start the problem is write the following: 28 = 256 27 = 128 26 = 64 25 = 32 24 = 16 23 = 8 22 = 4 21 = 2 20 = 1 130 = 128 + 0 + 0 + 0+ 0 + 0 + 1 + 0 = 10000010 in binary
Why would you want to use a String variable instead of a char variable to identify the name of your favorite color?
The names of colors can require more than one character to spell. For instance, "red" requires 3 characters, and cannot be stored in a single char.
Screenshots in your assignment submissions should contain what?
The output of your program
Since the private instance variables of a class are not directly accessible in its subclasses, how can the methods of a subclass access the values of these private instance variables?
They can be accessed through the parent classes public or protected methods, which are accessible to subclasses.
Theorize why you might want to set an object reference to null.
This is how you would "delete" an object from a reference. If the reference (the variable referencing the object) is set to null and it is the last variable referencing that object, then the object will be deleted (garbage collection in Java is automatic).
I've written a basic application which asks the user for a single integer. It then uses an if-else statement to print a message to the user, telling the user if their input was even or odd, and then terminates. I then decide to test the program once; I enter '6' and the program prints a message saying '6 is even'. I conclude that my program works. Explain my error.
This program has 2 possible paths it can follow in the if-else statement, one for even and one for odd. The program should be tested with AT LEAST 1 even and 1 odd number to test each path, if not multiple odds and evens.
How do you copy an array into another?
To copy any array, you need to: Create a new array with the same type and length. Using a loop, copy each element of the original array into the new array. If the elements of the original are primitives, they will be passed by value, so the copied array elements can simply be assigned the values of the old elements. If the elements of the original are objects, then copies of those objects should be made by constructing new objects and copying the data from the original objects into the copies.
Give a couple of reasons why you would use the DecimalFormat class?
To format a number as a currency or a percentage. To display a rounded version of a number without actually rounding the data.
URL stands for _____
Uniform Resource Locator uniform resource locator
In the most common convention, constants are written in
UPPER_SNAKE_CASE
If we declare total and count as integers, then the average will be calculated using integer division. What problem does that create, and how can it be solved?
Use floating point division by casting either the total or count as a double or float.
Assuming the class B inherits from class A and method foo belongs to class A, what do we mean by overriding method foo in class B?
We are coding another version of method foo in class B
A way to convert a primitive data type into an object is to use ________ classes
Wrapper wrapper
!( a > 3 ) is equivalent to _________________ .
a <= 3
What is each execution of the loop body called?
an iteration
An abstract class is declared to be abstract by including the __________ keyword in the class header.
abstract
. is the __________ operator.
access
The name of the method that enables us to append an element to the end of an ArrayList is ________.
add
When we instantiate an array without specifying values,
all of these answers are correct
A Java escape sequence starts with a _____
backslash back slash \
The position of an element within an array is known as its ______________
index
Inside the block of a switch statement, the value of the expression is compared to the _________________ constants in order.
case
An ArrayList automatically ___________its capacity as needed.
changes expands increases
The method called when instantiating an object is a _____________
constructor
A constructor's primary purpose is to __________
create a class instance
In the following statement: for ( Auto current : autos )
current represents the Auto object that will be processed inside the loop body
The _________ allows you to step through program execution statement-by-statement, watching the values of variables change.
debugger
Inside the block of a switch statement, the keyword that plays the same role as else in an if or if/else if statement is _________________
default
A constructor which takes no arguments is generally called a __________ constructor.
default DEFAULT Default
When reading a data from an input file, we can test whether we have reached the end of the file by calling a ________ method of the Scanner class
hasNext
Inheritance helps organize related classes into _________________.
hierarchies hierarchy
Constructors are called with the ________ keyword.
new
The class members associated with objects (as opposed to the class itself) are called _____
non-static instance variables nonstatic
Assuming number is an int variable, write a statement using a shortcut operator equivalent to this one: number = number * 5;
number *= 5;
What are 3 ways to add 1 to an int variable named number which has already been declared and initialized?
number = number + 1; number += 1; number++;
An identifier of an object is an _________________.
object reference
The switch statement can be used instead of an if/else if statement.
only when comparing the value of an expression to a char, integer, or String constant
The access modifier of accessor and mutator methods is usually _____
public
Methods in a Java interface without modifiers are implicitly
public and abstract
The division operator / returns the _________________ of the division between 2 numbers.
quotient
Objects are passed by ________
reference
The modulo operator % returns the ________ of the division between two numbers
remainder
The name of the method that enables us to delete an element at a specified index in an ArrayList is ___________.
remove
The region of a program where a variable can be referenced, or used, is called the _______ of the variable.
scope
Looking for a value in an array by looping through all the elements of an array in order is called _________________ search.
sequential linear
With the boolean expression a && b, if a is false, the JVM does not evaluate b. This is called _____________
short circuit
If a method is overloaded, the different versions of the method must have different _________
signatures Signature Signatures signature SIGNATURE SIGNATURES
char values are surrounded by _____ quotes
single
What is the name of the method that returns the number of elements in an ArrayList object?
size
Why does Java provide a protected access modifier?
so fields and methods can be inherited by subclasses without being public
Class B inherits from class A. Class A is class B's _______ class.
super
this refers to
the instance through which an instance method was called