Programming Exam Flashcards
Do the nested loops need to be the same loop type?
No, the nested loops do not need to be the same loop type.
When can nested loops be useful?
Nested loops can be useful if we are performing multiple operations, each of which having its own count or sentinel value
What is important about the inner (nested) loop ?
The inner, nested loop executes completely (executes all its iterations) for each single iteration of the outerloop
When does a loop repeat a set of operations for each input item?
A loop repeats a set of operations for each input item while a condition is true
What is the while loop especially useful for?
The while loop is especially useful for event-controlled looping.
How does a while loop work?
A while loop executes a set of operations in the loop body as long as the loop condition is true. Each execution of the loop body is an iteration of the loop
What occurs if the loop condition evaluates to false the first time it is evaluated?
If the loop condition evaluates to false the first time it is evaluated, the body of the while loop is never executed
What occurs if the loop condition never evaluates to false
The result is an infinite loop
How does event-controlled looping work
In event-controlled looping, processing of items continues until the end of the input is signaled either by a sentinel value or by reaching the end of the file
What is a sentinel value
A sentinel value is a special input that signals the end of the items to be processed.
What is the normal flow of control with a sentinel value
A priming read is performed before the while loop, then the body of the loop processes the input and then performs an update read on the next data item
How can we test that we have reached the end of the file when reading from an input file
We can test whether we have reached the end of the file by calling a hasNext method of the Scanner class
Describe the general setup of an accumulation programming technique
A total variable is initialized to 0 before the loop starts, then in the loop body we add each input value to the total. When the loop completes, the current total is the total for all of the processed input values
Describe the general setup of a counting program technique
Initialize a count variable to 0 before starting the loop. In the loop body, we increment the count variable for each input value that meets our criteria. When the loop completes, the count variable contains the number of items that met our criteria
Describe the general setup of finding an average
We have to combine accumulation and counting. We add the input values to the total and increment the count. When the loop completes, we calculate the average by dividing the total by the count. Before computing the average though, we should verify that the count != 0
Describe the general setup of finding a maximum or minimum value
We assign the first input to a running maximum or minimum. In the loop body, we compare each input value to our running max/min. In the loop body, we compare each input value to our running max/min. If the input value is less than the running min, we assign it to the running min. If it is greater than the running max, we assign the input value to the running max. When the loop completes, the running value is the max or min of all of the input values
How do we avoid generating exceptions when the user types characters other than the data type expected
We use the hasNext methods of the Scanner class
How do we construct a loop condition
We must construct the inverse of the loop termination condition
What are important things to test when testing a program that contains a loop?
Test that the program produces correct results by inputting values and comparing the results with manual calculations (avoid logical errors), also test that the results are correct if the loop body never executes. The final thing to test is what occurs when an invalid input is entered.
In what order does the do/while loop check the condition/execute the loop
The do/while loop checks the loop condition after executing the loop body.
How many times (minimum) does a do/while loop execute
A do/while loop executes at least once because the condition is checked after the loop body is executed.
When is it useful to use a do/while loop
When you want to validate input
Why/When are for loops used
The for loop is useful for count-controlled loops, aka loops in which the number of iterations is known before the loop begins
Briefly explain how for loops are executed
When the for loop is encountered, the initialization statement is executed. Then, the loop condition is evaluated. If the condition == true then the loop body executes. the loop update statement is then executed and the loop condition is reevaluated. If the loop condition is still true, it continues so on until the condition evaluates to false
How do we use a loop control variable in a for loop
We set its initial value in the initialization statement, and then increment or decrement its value in the loop update statement and then check its value in the loop condition.
What are the important things to test in a FOR loop
Test that the starting and ending values of the loop variable are correct. It is also important to test an input for which the loop body does not execute at all.
Describe user defined classes
A class that is written by a user that is used to encapsulate data and methods to then be used by application/service classes
What is a major benefit of incorporating methods that work with data into our class
Being able to hide the details associated with handling that data.
Give examples of data/functionality that could be encapsulated by classes
A person, a place, a thing, or more generally an object. A student, a college or a course..
Whats the common syntax related to class names
They are nouns and start with a capital letter
What goes inside the curly brackets in a class
The data of the class (fields) and methods.
Whats an important function performed by the class methods
Maintaining the values of the class data for client programs
What is another name for the data of the class
A field
What is a client program
The users of a class
What is the use of an access modifier?
Specifies where the class or member can be used.
What needs to be provided for each class and each member of the class?
An access modifier must be provided
What are all the possible access modifiers?
public, private, protected or no modifier at all
What occurs if you put no access modifier
The package is able to be accessed
What does the public access modifier allow for
The public access modifier allows the class or member to be used, or referenced by methods of the same or other classes.
What does the private access modifier allow
Allows the class or member to be used, or referenced, by methods of the same class
What does (no modifier) package access allow
Package access specifies that the class or member can be accessed by methods in classes that are in the same package or in the same folder
What is data hiding?
When the APIs of the methods of a class are posted but not the method body (code of the class)
What do the instance variables of a class hold?
The instance variables of a class hold the data for each object of the class
What can we say about instance variables
That they represent the properties of that object
What can be said about the values of the instance variables
They can represent the state of the object
What modifier is typically used for non constant instance variables of the class AND WHY
The private modifier. This permits only the methods of the same class to set or change the values of instance variables. We can then say the data is encapsulated, or protected
What data type can an instance variable be
Any of java’s primitive data types of a class type
What does the identifierList contain
It consists of one or more names for instance variables of the same data type and can optionally assign initial values to the instance variables
How do you separate more than once instance variable name
By using a comma
What is the naming convention for instance variables
Identifier names for instance variables are nouns and begin with a lower case letter and internal words begin with a capital letter (CAMELCASE)
What is the scope of the fields of a class
It is a class scope
give an example of instance variable definitions
private String name = “”;
private final int PERFECT_SCORE = 100, PASSING_SCORE = 60;
What should be defined as instance variables
Define instance variables for the data that all objects will have in common
What is the function of a method caller?
The method caller sends arguments or actual parameters to the method
What are formal parameters?
Actual parameters that the method refers to
What is the naming convention for methods
The method name should begin with a lowercase letter and with internal words usually having a capital letter. They’re typically verbs
What status is required for the access modifier for methods that provide services to client
A public status
What status is usually reserved for methods that provide services only to other methods of the class
A private status
What is the return type of a method
The data type of the value that the method returns to the caller.
What are examples of valid return types for a method
Any of java’s primitive data types, any class type or void
What is special about methods with a return type of void
They do not return a value to a caller
What is the body of a method comprised of (general terms)
The code that performs the methods function. Written between beginning and ending curly braces.
Are the curly braces for method required?
Yes, these curly braces are not optional. They are required regardless of the number of statements in the method body.
What are two examples of error that can result if you forget one or more curly braces
illegal start of expression
OR
’;’ expected
What can be done in a method body?
A method can declare variables, call other methods, use: if/else statements, while loops, for loops, switch statements and do/while loops
Do all objects of a class have their own copy of the class methods?
No, all objects of a class share one copy of the class methods
What is the purpose of a return statement?
A return statement is a value returning method that sends back its results to the caller using the return statement.
Does the data type of the expression need to match the return type of the method?
yes, it must match
How is a value returning method called
A value-returning method is called from an expression and when the method completes it operation, its return value replaces the method call in the expression
How can the return statement be used if the data type of the method is void
You can use the return statement without an expression (return;) or omitting the return statement all together
Why can you omit the return statement if the data type of the method is void
Because control automatically returns to the caller when the end of the method is reached.
What is a constructor
A constructor is a special method that is called when an object is instantiated using the new keyword.
How many constructors can a class have
As many as they want
What is the job of the class constructors
To initialize the fields of the new object
What is the naming convention for a constructor
To have the same name as the class
What access level status are constructors set to
They should be set to public so that applications can instantiate objects of the class
What are the two ways that values can be assigned to constructors
A constructor can either assign default values to the instance variables or the constructor can accept initial values from the client through parameters
Is it mandatory to have a constructor for a class
No it is optional
What occurs if no constructor is written for a class
The compiler will provide a default constructor
What is a default constructor
A constructor that takes no arguments
What does a default constructor do
The default constructor assigns default initial values to all instance variables
What is autoinitialization
When a default constructor assigns default initial values to all instance variables
What is the default constructor assignment for numeric variables
the value of 0
What is the default constructor assignment for characters
unicode null character
What is the default constructor assignment for boolean variables
The value of false
What is the default constructor assignment for object references
null
What occurs if you provide a constructor but have instance variables that are not initialized?
They will be given the predefined default value
If we provide a constructor, does the compiler still generate a default constructor?
No it doesn’t.
What type of reference are strings considered
Object references
Because a class is considered a “caretaker of it’s fields”, what is the classes responsibility?
It is the classes responsibility to ensure that the data for each object is valid.
What constitutes a valid value for an instance variable?
A valid variable depends in part on the data type of the variable and in part on the class and it’s design decision.
How do classes handle invalid argument values?
It can either generate an exception or substitute a default value - depends on design decision.
What does overloading a method mean?
Providing multiple constructors for the method
How do we overload a method
We provide the method with the same name but with a different number of parameters, or with the same number of parameters but having at least one parameter with a separate data type
What is a methods signature
The name of the method, along with the number, data types and order of its parameters
Is the return type part of a methods signature
No it is not
What occurs when a client calls a method that is overloaded
Java determines which version of the method to execute by looking at the numbers, data types and order of the arguments in the method call
What is a general statement we can make about arguments sent to an overloaded method
Arguments sent to an overloaded method must match the formal parameters of some version of that method
What type of scope do instance variables have
A class scope, meaning they can be accessed anywhere in the class
What type of scope do methods have
A class scope, meaning they can call any of the methods in the class regardless of whether they have been declared private, public or protected
What else can a method access besides the instance variables
A method can also access its own parameters
What type of scope do a methods parameters have
A local scope so it can access its parameters directly
If a variable is defined within a method, what properties does it have?
These variables have a local scope and are accessible from the point of definition until the end of the method or the end of the block in which the variable was defined
What error occurs if you attempt to use an identifier that is not in scope
cannot find symbol
To summarize: A method in a class can access:
The instance variables of its class
Any parameter sent to the method
Any variable the method declares within its body from the point of declaration until the end of the method or until the end of the block in which the variable was declared
Any methods in the class
What is generally provided by the class if it contains private instance variables
Classes will usually provide public accessor methods for the instance variables
What arguments do “getters/accessors” take and what is returned
The method takes no arguments and simply returns the current value of the instance variable. The return type is the same data type as the instance variable
Why are mutator/setter methods provided to clients
To allow them to change instance variables
Since the instance variables are declared as private, what type of mutator/setter method is provided to the client
A public mutator is provided for any instance variable that client will be able to change.
What is the return type for setters/mutators
void
What is the naming convention for setters
the name of each mutator method starts with a lowercase word set followed by the instance variable name with an initial capital letter
What should be validated before allowing the mutator to work
The body of the mutator method should validate the parameter value passed by the client. If valid - the mutator assigns that value to the instance variable
What is a common error with writing mutator methods
The common error with writing mutator methods is using the instance variable name for the parameter name.
What occurs if a method parameter has the same name as an instance variable
The parameter hides the instance variable due to the name precedence.
How does the method know which objects data it should get, set or use to calculate a value?
Using the special object reference named THIS
What is the implicit parameter
When a method begins executing, the JVM sets the object reference, THIS, to refer to the object for which the method has been called.
What occurs when a method references an instance variable
It will access the instance variable that belongs to the object that the implicit parameter references. An instance variable referred to by a method is considered to be this.instanceVariable
Give an example of how you would setModel to model using the THIS object reference
public Auto setModel (String model) { this.model = model; return this; }
What is the benefit of returning THIS?
The benefit of returning this is that we can chain method calls.
What is a dot operator?
The dot operator, also known as separator or period used to separate a variable or method from a reference variable.
Give an example of chaining method calls
After THIS has been returned:
Model m = Model.create().withFieldA(“AAAA”).withFieldB(1234);
The dot operator associates in what order?
left to right
What is the function of toString
The function of the toString method is to return a printable representation fo the object data
What is the function of the equals method
The equals method is designed to compare two objects for equality.
What is commonly misunderstood about the equals method
The equals method takes an object reference parameter that is expected to be an Auto reference and returns true if the values of its fields are equal to the values of the fields of this Auto object, false otherwise.
What is overriding a method?
Providing the same header as the methods in the object class but providing a new method body.
Where should you add the @override annotation when overriding a method?
Before the method header
Why do we add the @override annotation
It tells the compiler that the method that follows is overriding a method inherited from another class. And, in turn, the compiler warns us if our method header does not infact override the inherited method
What operation does instanceof perform?
evaluates to true if objectReference is of Classname type; false otherwise
What is the left and right operand of the instanceof binary operator?
The left operand is an object reference and the right operand is a class
As a principal, what should communicate directly with the client
The class methods should communicate directly with the client and the client should handle the communications with the user
How do you determine whether or not something should be static
If it makes sense to call the method before an object has been constructed then it should be static (ie: method for converting speeds.. can be used even without having a specific car object has been constructed)
Can static methods access instance variables?`
No, they cannot access instance variables because static methods are associated with a class and not an object
Can static methods access static class variables?
Yes they can
Can static methods call static class methods
Yes they can
Can static methods call non-static instance methods?
No they cannot
Can static methods use the reference “this”
No they cannot
What is another name for a non-static method
An instance method
What can an instance method reference
An instance method can reference both class variables and instance variables, as well as class methods and instance methods
What is an array?
A sequence of variables of the same data type
What data types are accepted in an array
int, float, double, byte, boolean, char, short, long or a class.
What is each variable in the array considered
an element
What is the index of an array
the array name and subscript that refers to the elements position in the array
How are arrays implemented into java
arrays are implemented as objects in java
How do you create an array
- Declaring the object reference for the array
2. Instantiating the array
What can be said about an array of objects?
Each element is an object reference which stores the location of an object
How do you declare an array
We have to specify the name of the array and the data type, as we would for any other variable
Give an example of the syntax of an array
double [] dailyTemps; // each element is a double
Give an example of the syntax of an array using a boolean
boolean [] answers; // will hold true or false values
Give an example of the syntax of an array using 3 int values
int [] cs101, bio201, hist102; // all elements are int values
Does declaring an array allocate memory for the array?
No, it does not.
What does specifying an array do
It does not specify how many elements the arrays will have. The declaration simply specifies an object reference for the array and the data type of the elements
What is the syntax for instantiating the array that contains n elements
dailyTemps = new double [n]; // daily temps has n elements
How do you allocate memory for an array
You instantiate it
Can you combine declaration and instantiation of arrays?
Yes
What is the syntax for combining declaration and instantiation of an array with n elements
double [] dailyTemps = new double [n];
When is the only time an initialization list can be given with an array
When the array is declared.
How can you instantiate an array by assigning initial values?
datatype [] arrayName = { value0, value1, value2, .. }; // valueN is an expression that evaluates to the data type of the array and is the value to assign to the element at index N
What is special to remember about instantiating and assigning initial values to arrays
There is no new keyword used and there is no size specified for the array. The number of elements is determined by the number of values in the initialization list
What is always the index of the first element in an array
0
What is always the index of the last element in the array
n-1
What is an index in an array
An elements position within the array
What is the instance variable length used for with arrays
it holds the number of elements in an array
What is the syntax for using the instance variable length in an array
arrayName.length
What are the two required steps to instantiate an array with a class data type
- instantiating the array
2. instantiating the object
What is the syntax for calling an object in an array
Use the array name and index along with the dot notation
How would you approach printing all elements in an array
We have to use a loop that prints each element individually
Give an example of a loop to print all elements in an array
for (int i = 0; i < cellBills.length; i++)
{
system.out.println (i + “\t” + cellBills[i]);
}
How do you approach reading and summing the data into an array
Using for loops to prompt the user to enter data into the array
How do you approach finding max or min values in an array
Using a loop to find a minimum and maximum value and note both indexes
How would you approach copying an array
Use a for loop to assign a backup to each individual element
How would you expand the size of an array while maintaining the values of the original array
- Instantiate an array with the new size, giving the new array a temporary reference
- Copy the elements from the original array to the new array
- Point the original array reference to the new array
- Assign a null value to the temporary array reference
How would you compare whether two arrays are equal
- Determine if they are equal in length
2. Use a for loop to compare the coresponding elements in each array
Why can you not use the == to compare two arrays
Because arrays are objects, so using the equality operator will compare whether the two array references point to the same array in memory, not whether or not the data in the two arrays are equal