COSC 1 P02 - Final Exam Review (Fall 2019) : 1 Words and Definitions
COSC 1 P02 - Final Exam Review (Fall 2019) : 1 Words and Definitions
Maysara Al Jumaily
th
Tuesday December 10 , 2019
Library: A library is a collection of previously compiled code that can be used in future. For example,
BasicIO is a library written by someone which we are using now.
API: (Application Programming Interface) is a description of the resources (classes and methods) provided
by a library.
Package: A collection of classes within a Java program. For example, we use a package when dealing with
multiple classes.
Global/Instance variable: Variables defined at the class level and are accessible anywhere in the class.
Scope (of a variable): The visibility of the variable (the region where a variable is accessible). For exam-
ple, a global variable is visible/accessible anywhere is the class.
Method: A component of a Java class which contains some code. It represents a functionality/behaviour
of the class.
Cascading method call: A chain of method-calling. For example:
pic.getPixel(0, 0).getColor();
1
Formal parameter: The variable name and type defined in method declaration. For example:
public void multiply(int x, int y){...}
Actual parameter: The values inserted when calling a method. For example: multiply(7, 3);
Value parameter: The value of the variable is copied over to the formal parameter, i.e., passing the value
not the variable itself. For example:
int num1 = 5;
int num2 = 8;
multiply ( num1 , num2 ) ; // equivalent to multiply (5 , 8) ; we are creating
a copy of the values of num1 and num2 and passing them . We pass
the values , not the variables .
Object: Something that has states (characteristics) and behaviours (functionalities). States are the in-
stance/global variables whereas behaviour refers to the methods of the class. For example, the states
of a Turtle are direction, pen state and current coordinate on canvas. Some of the behaviours include
penUp, penDown, forward, backward, etc.
Object-oriented language: A programming language that allows the concept of objects (i.e., abstraction
and encapsulation). For example, Java is an object-oriented programming language.
Private: A keyword in Java which indicates a variable or method to be private. This means that other
classes cannot access them (encapsulation/information hiding).
Casting: A way to change the type of a variable. In Java, it is written by writing the desired type in
parentheses in front of the value. For example, int x = (int) 3.14;
Implicit type conversion: A type conversion (cast) which is done automatically by Java. For example:
double x = 10;//it automatically becomes 10.0
Narrowing conversion: The process in which a type is down cast to another type usually losing precision.
For example, converting a double to int.
Collection: An object which holds sub-objects, i.e., Picture holds Pixels, Sound holds Samples.
Garbage collection: A way for Java to reclaim memory which is not used anymore.
Reference Variable: A variable which represents an object or an address in memory rather than a value.
EOF: End Of File is the condition (state) that become true when an attempt is made to read data from
the file but no further data available to be read.
Algorithm: A well-defined sequence of steps to solve a problem (the recipe of a program).
Page 2
Switch statement: A more compact way of if, else if, else if, · · ·, else if, else statements. It
accepts a value and checks the possible cases.
Persistent object: Extending an object’s lifetime so that it is written to hard drive and will not vanish
after the program closes.
serialVersionUID: A constant that may be specified for a Serializable (persistent) object. It specifies a
unique key that differentiates objects of this class from objects of other classes that have been written
to hard drive. The compiler can verify that the object read is of the correct type and version.
Garbage collection: The process of discovering unused memory and clearing it for reuse.
In-test loop: A loop in which its condition is neither the first operation in the loop, nor the last. It is
within the loop. This means that the statements of the loop body are in two parts: the part before
the condition which is executed 1 or more times and the part after the condition which is executed 0
or more times. There is no in-test loop in Java but we can build one using an if statement:
while ( true ) {
// the part before the condition , runs once at least
if ( file . isEOF () ) { // in - loop condition
break ;
}
// the part after the condition , possible to run zero times .
}
Page 3
C) Instance variable vs Local variable
Instance variable is visible/accessible from the creation of the object until the object is garbage-
collected.
Local variable is declared within a method and is visible/accessible only when executing the method.
D) Formal Parameter (parameter) vs Actual Parameter (argument)
Parameters are found in the method header. They have a type and name. For example,
public void multiply(int x, int y){...}
Arguments are the actual values that are passed when method is called, i.e., multiply(7, 31);
E) Constructor vs Method
A constructor is a special kind of method that doesn’t have a return type and its name must match
the name of class. It is executed when an object is initialized.
A method is executed by an object after the object’s creation. It represents a behaviour of the
object.
F) Narrowing conversion vs Widening conversion
Narrowing conversion occurs when converting a larger set of values (i.e., double) to a smaller one
(i.e., int) which usually results in loss of information.
Widening conversion occurs when converting a smaller set of values (i.e., int) to a larger one (i.e.,
double) which doesn’t lose information.
Java will automatically perform a widening conversion whereas narrowing conversion requires the
programmer to explicitly cast.
G) Downcast vs Upcast
Downcast occurs when the type of the object is broader and is changed to a subtype (specific type).
For example,
Item anItem = (Item) invData.readObject();//we read an object (broader) but
casted it to Item (more specific).
Upcast occurs when the type of the object is specific and is changed to a supertype (broader type).
For example,
invData.writeObject(anItem);//we write the item (more specific) as an object
(much broader).
H) Private vs Public
public and private are access modifiers that can be placed on an instance variable or a method.
private: makes instance variable or method accessible/visible only within the class itself. Other
classes cannot access them.
public: makes instance variable or method accessible/visible anywhere (within the class and from
other classes).
A complete example:
public class Test {
private int x = 31; // global variable accessible only within
this class
public int y = 0; // global variable accessible anywhere
public Test () {...} // constructor , accessible here and from other
classes
private void sayHello () {...} // method accessible only within
this class
public static void main ( String args []) {
Test t = new Test () ;
}
}
Page 4
I) Iterative for-loop vs For-each loop
Iterative for-loop: An index variable is used which has starting and ending positions. The body
loop is executed known amount of times. For example:
for ( int i = 0; i < 10; i ++) {
// the body is executed known amount of times (10 times in this
case ) .
}
For-each loop: No index used and the body loop is executed unknown amount of times. It is used
to loop through each element in a collection (i.e., Pixels in a Picture). For example:
for ( Pixel p : picture ) {
// the body is executed as long as we still have more pixels to
visit ( we don ’t know the exact number ) .
}
K) Coupling vs Cohesion
Both are properties of a class structure that measure the quality of the design.
Coupling is how strongly a class is connected to other classes.
I Loose coupling: A class having sufficient privacy (usage of private keyword more often).
I Tight coupling: A class that doesn’t have privacy (usage of public keyword instead).
Cohesion is what can the class do.
I Low cohesion: methods are board.
I High cohesion: methods are specific and well-defined.
I For example:
// The next two methods show high cohesion ( they are more specific
and well - defined )
public void setNum1 ( int x ) {
num1 = x ;
}
public void setNum2 ( int y ) {
num2 = y ;
}
A good design has loose coupling and high cohesion.
Page 5
L) Picture vs Sound
Picture:
I Picture: a collection of pixels (a 2D rectangular table of rows and columns of cells).
I Pixel: The basic unit of a Picture. A Pixel is a cell that holds one and only one Color.
I Color: An object that is made of three ints: red, green and blue. Each int is a number between
0 and 255. There will be 256 × 256 × 256 = 2563 = 16, 777, 216 different colors.
Picture
(0, 0)
(x, y)
Pixel Color
= (R, G, B)
= (245, 66, 158)
Where R, G, B are int between 0 and 255
(4, 4)
32767
Sound
Sample
Amplitude
Amplitude
· · · n − 1 Samples
0
0 1 2 ···
−32768
Page 6
3 Long Answers
Provide an in-depth and complete answer for the following:
1. Describe the steps in the execution of a function method. Include reference to argument
(actual parameter), parameter (formal parameter), method body and return statement.
The following happens when a function method is called (with the code snippet below):
// constructor .
public Test () {
int total = multiply (3 + 4 , 5 + 1) ;
}
public int multiply ( int x , int y ) {
return x * y ;
}
The arguments (actual parameters) are evaluated i.e.,
int total = multiply(3 + 4, 5 + 1);
becomes
int total = multiply(7, 6);
The values of the arguments are copied to the parameters (formal parameters).
The calling code is suspended (we change the flow of execution and run the method first).
The method body is executed.
The return value is computed.
The calling code is resumed (go back to where we left off) with the return value.
2. Describe how a picture is digitized. How is grey represented? Why is it reasonable for a
color channel to be limited to the range 0–255?
A Picture is a grid (rows and columns) of Pixels (refer to Figure 1). A Pixel holds one and
only one Color. A Color is represented by three color integer channels: red, green and blue.
Each of the channel stores an int between 0 and 255 (including 0 and 255).
Grey is produced when the three color are equal i.e., red = green = blue. We only have 256
possibilities: (0, 0, 0), (1, 1, 1), · · · , (255, 255, 255) where (0, 0, 0) is black and (255, 255, 255) is
white.
The human eye can distinguish about 16 million different colors. Using 1 byte for each color
channel, we can generate 256 different combinations. Having three color channels generates
256 × 256 × 256 = 2563 = 16777216 (16.7 million) different combination of colors which is
enough for human vision.
3. There are three types of for loops: indexing (iterative) for, for-each and for-ever. Compare
the three and describe a situation in which you would use each.
The iterative loop:
for ( int i = start ; i < limit ; i ++) {...} // syntax
for ( int i = 0 ; i < 10 ; i ++) {...} // first example
for ( int i = 0 ; i < 10 ; i = i + 2) {...} // second example
i is the loop index that has defined starting and end positions. The loop executes the body
once and then increments i until the condition is false. The number of times the loop executes
is known.
The for-each has the form:
for ( type e : c ) {...} // syntax
for ( Pixel p : picture ) {...} // example ( read as " for each pixel p
in picture ")
Page 7
where c is a collection of elements (i.e., Picture or Sample). The loop repeats with the index
e being each of the elements of c. This loop is used when all the elements of a collection must
be processed. We don’t know the number of times we will loop.
The for-ever loop has the form:
for ( ; ; ) {...} // syntax and example
It is an infinite loop, never terminating on its own. It is typically used to construct an in-test
loop by including an if and break statement within the loop to terminate. Also,
for ( ; ; ) {...}
is exactly the same as
while (true) {...}
.
4. What, exactly, is a main class? Is a package limited to a single main class or can there be
several? Why would you want several? How does execution begin within a main class.
A main class is a class that contains the main method.
A package may have any number of main classes.
We use several main classes to complete chunks of our overall task. For example, in lab 10, we
had a main class that converted the information of a .txt file to .bin. We then had another
main class that allowed us to select .bin file as input and outputted its content on screen.
The first thing Java executes is the main method after clicking the Run button. The body of
the main method is then executed line by line.
5. When designing classes, some members (instance variables and methods) are declared
private, and others public. Why? What is the benefit of using accessor/getter functions
instead of making instance variables public? What about updaters? Why would you
include a private method in a class?
Instance variables are normally declared private.
Methods that provide the behaviour of the class are declared public.
Declaring instance variables private ensures that their values can only be accessed or modified
by code within the class making the class more secure.
A class can restrict operations on instance variables using the private keyword.
It has accessor methods only for those instance variables whose values should be known outside
the class. Also, updater methods which allow the class to ensure correct update of the values
of instance variables. For example:
private int days = 0; // say , for example , we don ’t have negative
days .
.
.
.
public int getDays () {
return days ;
}
public int setDays ( int updatedDays ) {
if ( updatedDays >= 0) { // positive or zero
days = updatedDays ;
} else {
// negative don ’t do anything
}
}
Page 8
6. We’ve seen two techniques for processing the pixels in a picture: a for-each loop and an
iterative for loop. What are two advantages of the for-each? What are two advantages of
an iterative for?
The for-each loop automatically loops through all pixels (top to bottom, row by row) in a
picture avoiding errors like (PixelOutOfBoundsException) or visiting a pixel more than once.
We don’t declare an extra variable to get current pixel, we use the variable in the loop, i.e.,
for ( Pixel p : pic ) {
// current pixel we are visiting can be referred to as p .
}
The iterative for loop allows us to visit pixels in any order and we can specify a part of the
picture to loop though. For example:
for ( int i = 10; i <= 100; i ++) {
for ( int j = 15; j <= 25; j ++) {
Pixel p = pic . getPixel (i , j ) ;
}
}
7. Every object occupies storage, what is that storage used for? What is the purpose of a
constructor? We say that an object’s behaviour depends on its state, what does this mean
in practical terms (regarding methods and instance variables)? In the payroll program us-
ing an Employee class discussed in lecture, we created a new object for each employee. Why
doesn’t the program run out of memory even if the company has thousands of employees?
An object needs storage to store its instance variables (state) in memory.
A constructor makes an object valid by initializing the instance variables appropriately.
The state of an object is represented by the values of the instance variables.
The behaviour of an object is the result of executing the object’s methods.
Executing a method (a behaviour of class) depends on the values of instance variables as code
in methods uses the state (instance variables) of the object.
The storage of an object becomes garbage whenever there are no longer any variables referencing
the object. For example, the local variables in a method become garbage when the method is
done execution. Java will automatically wipe them off (known as garbage collection).
Since the payroll program references only one object at a time (i.e. there is only one Employee
variable), the storage for prior employees is garbage collected and memory is conserved. We
override the information every time we read a new employee from the file.
8. Explain difference between & vs &&. How about | vs ||?
Java has four compare operators: &, &&, | and ||.
When using &, both sides of & must be true and both sides are checked.
When using &&, both sides of && must be true. We first check left side to be true, if yes, we
proceed to check the right side, if not, then we don’t check right side. Also called short-circuit
(smart/lazy approach).
When using |, at least one of the sides of | must be true and both sides are checked.
When using ||, at least one of the sides of || must be true. We first check left side to be true,
if yes, we don’t proceed to check the right side, if false, only then we check right side. Also
called short-circuit (smart/lazy approach).
9. What is the difference between a local variable and an instance variable? How do you
declare each? When would you declare a variable as an instance variable and when as a
local variable?
Page 9
A local variable is a variable which is declared within a block { ... } i.e., in an if statement,
for loop or a method. It is not accessible (not visible) outside of the block. For example:
for ( int i = 0; i < 10; i ++) { // i is declared here
// i is visible here
}
System . out . println ( i ) ; // error as i is not visible here
Post-test: checks the condition after executing the body (the body must run 1 time at
minimum). For example:
int x = 0;
do {
// body will always run at least 1 time even though the
condition is false
} while ( x == 1) ;
In-test: checks condition within the loop. It can be expressed by using a for-ever loop and
an if statement:
for ( ; ; ) {
// the part before the condition , runs once at least
String s = file . readString () ;
if ( file . isEOF () ) { break ;}
// the part after the condition , possible to run zero times .
}
Use pre-test loop when the body must be executed zero or more times.
Use post-test loop when the body must be executed one or more times.
Use in-test loop when some statements must be executed one more time than the rest of the
statements.
Page 10
11. Differentiate between widening and narrowing conversions and between up-cast and down-
cast. Which does the compiler do implicitly and why? What is the difference between a
cast that causes a narrowing conversion and a down-cast?
Widening conversion is converting from smaller type to a larger type (i.e., int to double) with
no loss of information.
Narrowing conversion is converting from larger type to a smaller type (i.e., double to int)
and loss of information may occur.
Up-cast is a cast from a subtype (specific) to a supertype (broad), i.e., from Item to Object,
similar to widening.
Down-cast is a cast from a supertype (broad) to a subtype (specific), i.e., from Object to Item,
similar to narrowing.
A widening conversion and an up-cast are done implicitly (automatically by the complier)
because there is no loss of information.
A down-cast changes the type from a subtype to a supertype, not the object nor its represen-
tation.
A narrowing conversion changes the actual value, hence, changing the representation, i.e.,
int x = (int) 3.14;//we changed the actual value to 3
12. What is abstraction? Why is it useful? What are the two ways to achieve abstraction in
Java?
Abstraction is the approach of thinking about the overall/broad idea not the details. It allows
to breakdown a complex problem into smaller pieces. It is useful because we can focus on
smaller pieces and code them easily, the complexity of the problem becomes easier.
The two ways are procedural abstraction and data abstraction:
I Procedural abstraction is a method in Java. It describes a specific set of actions and requires
the method name be specified for execution. For example, the method
private void buildForm(){...}
will contain the code to build the form. It needs to be called (i.e., buildForm();) to be
executed.
I Data abstraction is a class in Java. A complex problem is divided into smaller pieces (each
piece is a class). A piece/class will have its own (instance variables/state) hidden from other
classes. Then, classes can communicate with each other via methods (behaviours/function-
alities) to solve the original complex problem.
13. Objects have state and behaviour. What are these? How are they defined in a class?
Behaviour may depend on state and may modify state, how does this happen (i.e. what kind
of code)? Give an example of behaviour depending on state and of behaviour modifying
state for both a Turtle object and an ASCIIDataFile object.
State is the set of characteristics that represent an object. It differentiates one object from
another.
Behaviour is the set of functionalities that an object may perform.
State is defined as the instance/global variables in a class. These values are independent in
each object and are accessible in all methods in the class. Behaviour is defined by the public
methods of the class, which can access and/or modify instance variables.
A method may access instance variables to affect its execution (i.e., in an if statement). A
method may also change the value of an instance variable, potentially causing a different
behaviour by other method(s).
In Turtle, the action of the forward method depends on where the turtle is, the direction it
is facing, etc. When moving a turtle, the position of the turtle changes (i.e. its state). In
ASCIIDataFile, the action of a read method depends on whether or not the file is at the end
(EOF, part of the state of the object). If the object cannot read another item (because there
are no more), it changes the state to EOF.
Page 11
14. What is garbage? How does garbage come about? What is garbage collection? Why does
Java provide garbage collection?
Garbage is used storage (in memory) that is no longer needed.
Garbage occurs when objects are created, used and then no longer used by the program.
Garbage collection is the process of discovering unused storage (memory) and clearing it for
reuse. For example, you have a method that declare local variables. Once we execute the
method and leave, these local variables are still stored in memory, though, we cannot refer to
them. Hence, Java sees them as garbage.
Java provides garbage collection which reduce the memory used via a program by keeping only
active (non-garbage) variables/objects in memory.
15. What is a serialVersionUID? Why is it necessary for persistent objects? How is it used by
the Java runtime when reading objects? Why would you declare it rather than letting the
compiler generate one?
serialVersionUID is a unique number (global variable) associated with a class.
Persistent objects are written to/read from hard drive by possibly different programs. It is
necessary to ensure that the objects being read actually are objects of the class defined in
the program (i.e., there may be many Employee classes or the Employee class may have been
changed since the objects were written).
The Java runtime reads the objects and verifies the serialVersionUID of the object is the
same as the serialVersionUID of the class declaration in the program. If not, then an error
will occur.
In the case where a class is recompiled after objects have been created, the old objects may
not have the same serialVersionUID as the newly compiled class and the program will fail.
Java generates a serialVersionUID automatically if you forget to declare it. It is recommended
to declare it yourself as you can assign the serial number and increment it accordingly.
A)
for ( int i = 1; i <= 10; i ++) { Output
if ( i % 2 == 0 & i % 3 == 0) {
display . writeInt ( i ) ;
display . newLine () ; 3
} 6
else if ( i % 3 == 0) { 9
display . writeInt ( i ) ;
display . newLine () ;
}
}
Page 12
B)
x = 20; Output
while ( x > 2) {
x = x - x / 2;
10
display . writeInt ( x ) ;
5
display . newLine () ;
3
};
2
C)
x = 0; Output
for ( int i = 0; i < 5; i ++) {
switch ( i ) { 6
case 0 : { x = x + 3; } 9
case 1 : { x = x + 2; } 10
case 2 : { x = x + 1; } 10
} 10
display . writeInt ( x ) ;
display . newLine () ;
}
2. Given the following declarations and statements, what is output to the display in each part?
ASCIIDisplayer display ;
int num ;
int k ;
display = new ASCIIDisplayer () ;
A)
for ( int i = 1; i <= 10; i ++) { Output
if ( i > 4 && i > 2) {
5
display . writeInt ( i ) ;
6
display . newLine () ;
7
}
8
}
9
10
B)
num = 0; // we didn ’t have this line previously Output
k = 1; // we didn ’t have this line previously
for ( ; ; ) {
num = num + k ;
if ( k != 2 | k < 10) { 8
k = k + num ;
}
if ( k == 13) {
break ;
}
}
display . writeInt ( num ) ; // we didn ’t have this
Page 13
C)
k = 1; Output
num = 0;
switch ( k ) {
case 0: {
num = num + 3; 3
}
case 1: {
num = num + 2;
}
case 2: {
num = num + 1;
}
}
display . writeInt ( num ) ;
display . newLine () ;
B)
It crashes! As j becomes 0,
int i = 10; it will check both (left side
int j = 6; and right side of &) where
while ( j != 0 & ( i / j ) >= 1) { the right side will be i/0.
System . out . println ( " i is : " + i ) ;
System . out . println ( " j is : " + j ) ;
j - -;
i - -;
}
Page 14
C)
public class Test { Output
private int x = 7;
public Test () {
int x = 31; 31
System . out . println ( x ) ;
}
public static void main ( String [] args ) {
Test t = new Test () ;
}
}
int x = 2; int x = 2;
if ( x == 0) { switch ( x ) {
System . out . println ( " zero " ) ; case 0:
} else if ( x == 1) { System . out . println ( " zero " ) ;
System . out . println ( " one " ) ; break ;
} else if ( x == 2) { case 1:
System . out . println ( " two " ) ; System . out . println ( " one " ) ;
} else if ( x == 3) { break ;
System . out . println ( " three " ) ; case 2:
} else { System . out . println ( " two " ) ;
System . out . println ( " other " ) ; break ;
} case 3:
System . out . println ( " three " ) ;
break ;
default :
// equivalent to else {...}
System . out . println ( " other " ) ;
break ;
}
5. Why does this method gives an error (missing return statement) when compiled even though we do
have return statements?
The complier cannot guarantee
private String getSign ( int x ) { that one of the if statements
String result ; will run. Hence, in the case
if ( x < 0) { where no if statement executes,
return " negative " ; we reach at the end of the
} else if ( x == 0) { method not returning anything.
return " neutral " ; The fix is to change
} else if ( x > 0) { else if(x > 0){...}
return " positive " ; to
} else{...}
}
Page 15