Final Exam CMSC

¡Supera tus tareas y exámenes ahora con Quizwiz!

call stack

The internal structure that keeps track of the sequence of methods that have been called

What is hardware?

The physical components of a computer.

How are linked lists stored?

There is no pattern, can be all over the place

(True/False) The following could appear in an interface: public void f(int x);

True- prototype

Under what circumstances will the finally block run?

Under what circumstances will the finally block run?

Under what circumstances will the finally block run?

Whenever the try block is entered

Side effects

While expression is executed, something changes (ex: assignment, printing to console)

linked list

a collection of nodes arranged so that each node contains a link to the next node in the sequence

int a=7; int b= a++ + 4; c= ++a -3;

a=9 b=11 c= 6

add(E element)

adds the element to the end of the list

Under what circumstances will a finally block run? (Select all that apply.) >>A return statement is executed during the try block. >>The try block runs without any exceptions being thrown. >>An exception is thrown during the try block, and caught by one of the catch blocks below it. >>An exception is thrown during the try block, but is not caught in any of the associated catch blocks.

all

x=x+1 x++ ++x

all have the same side effect, but carry different values

2d rectangular

all rows are the same

Exceptions are thrown by

code you've written, code another person has written, that you are using, and by the JVM itself

What is "concatenation"? What operator do you use to concatenate Strings?

combine strings together + operator

What is the name of the Java interface that includes the compareTo method?

comparable

objects and call stack

does not hold the object, holds the memory address of where object is located

Strings being immutable is good because

doesn't create problems with aliasing.

printing ragged array

for (int row = 0; row < name.length; row++) { for (int col = 0; col < name[row].length; col++) { System.out.println(name[row][col] + " "); } System.out.println(i); }

If there is a tie

goes from left to right other than assignment

What does I/O stand for?

input and output

List the four Java primitive types that can be used to store integer values.

int byte short long

what happens to the runtime when the data set doubles? -- quadratic algorithms

it quadruples

What word describes one thousand bytes of space?

kilobyte

Rectangular 2d arrays- int [ ] [ ] a= new int [3] [4]; draw diagram

rows are automatically instantiated

==

same memory address

this.patch = other. patch

shallow copy contructor

(True/False) The following two code fragments are equivalent: for(String a = ""; x < 10; z = z + 7) {...} _______________________________________________________________ String a = ""; while (x < 10) { ... z = z + 7 }

true

(True/False) The following two code fragments are equivalent: if (x == 1) { System.out.println("A"); } else { if (x == 2) { System.out.println("B"); } }_______________________________________________ if (x == 1) { System.out.println("A"); } else if (x == 2) { System.out.println("B"); }

true

Declaring a 2D Array ragged normally

type [ ] [ ] name= new type [rows][ ]; name [index] = new type[cols];

x++

value is x before modification, then incremented

Are the elements of an array of references to objects initialized? If so, to what values?

yea, null

JUnit pros

you can write tests quickly

Pros of formal verification

you know for sure the code works

Exceptions are Objects, so

you must instantiate it before throwing it

Static methods

• method connected to the class, not an object • ex: Math.random • You do not declare a variable of Math type to get to the random method

List the following operators in order of precedence (highest precedence first, lowest precedence last). && = ! < +

! + < && =

What the output be? System.out.print("\"\"");

""

Inside of the "catch" you can do

"continue" so it skips an iteration where a degenerate triangle is created and doesn't decrease the trianglesNeeded counter (because continue skips all the code after the continue statement)

Give examples of "literals" of each of the following types: String, char, long, int, float, double, boolean.

"hi", 'x', 32L, 16, 15.7F, 373.2, true

What is software?

"programs" or "apps" that you can run on a computer

Which of the following could be used as names of variables in Java? We're not asking whether or not they are good style, just whether or not they are possible. (Select all that apply.) 7years $_hello55 this&that While

$_hello55 While

Will this work? public void foo(int x, long y) public void foo(long x, int y)

- if you pass two ints, java will not do the method call -if you pass in an int and a long, it will compile and it will run

Sets

- usually do not allow duplications -you add things to the set -you can only ask if something is in the set or not -no "last item" in the list -very fast

JUnit

-A unit testing framework for the Java programming language -make lots of short simple tests -tests run randomly -all tests will run even if one fails -if assertion fails test is aborted

Extends vs Implements What is similar?

-Both allow polymorphism -both allow final static constants -both allow static method implementation -both allow inheritance of public instance methods

Examples of higher level languages that WERE designed for object oriented programming

-C++ -Java

Big O of inserting at front of linked list

-Create node -assign the node to next item in the list -make head point to 1st node does not matter what size is, always 3 steps O(1)- constant

Examples of higher level languages that were NOT designed for object oriented programming

-Fortran -Cobol -C

What is an example of hardware?

-Monitor -keyboard -RAM -CPU

MyDouble wrapped a primitive double- could you do normal +, -, *, /?

-No, you cannot because it wrapped a double - These operations work with primitives but not MyDouble

What does the operating system do fo you...

-Process management -Memory management -Primitive I/O -Windowing -Primitive network control -Security management

Why do we have wrapper classes around primitives?

-These allow you to collect large quantities of data -all are immutable

What happens if an exception is thrown but not caught anywhere in your program?

-When an exception is thrown, Java looks for an appropriate catch block in the place where the problem occurred. -If a catch is not found there, then Java discards the current frame on the call stack, and looks for an appropriate catch block in the previous frame. -If none is found, that frame is discarded, etc. -If the exception is not caught anywhere, then the program terminates, and the exception propagates to the "out\ side world", which for us is the Eclipse IDE. Eclipse displays that red and blue error notification with stack trace in the console.

FancyWord class- There was one private String object that is wrapped by FancyWord What can you now do?

-You now can only use the methods within the fancy word class -FancyWord "wraps" the String -You can no longer use charAt( ), substring( ), or any other String methods -You cannot act on FancyWord like you act on a String anymore

wrapper class

-a class that has a single principle instance variable that is private -other public methods that allow the user to interact

Name different operating systems

-apple macOS -apple IOS -Microsoft Windows -Linux -Android

Java Collections Framework

-built in -most collections live in java.util -always contains references -rely on equals methods being implemented correctly

Limitations of for each loop

-cant loop through a part of the list -no index numbers -you cannot assign anything to the variable (think benji/spot example) -you cannot add or remove elements from the current list during the loop

To copy an array:

-create a new array (of the same length as the original, a.length) -use a loop to assign every value in array a to array b (b[i] = a[i] >> make sure the copy array is one left of the assignment operator and the original array is on the right side of the assignment operator)

Big O of accessing ith element in an array

-each box in an array is 4 bytes -java knows memory address at the beginning -a[n]= beginning memory address + 4 bytes * n -The same amount of arithmetic is done for each O(1)

If one person has a linear algorithm and someone else has a logarithmic algorithm which will run faster?

-eventually the lines will cross -in small values of n, straight line does better compared to the log curve -in larger values, log is faster than straight line

Changing an element in a deep copy

-extra bc hat class is immutable -wastes time and memory -for Ahat class, this is preferred bc you could access a[0].resize and change the hat that is aliased

Changing an element in a shallow copy(draw)

-has no effect on the original array of hats -okay because hat class is immutable, if mutable deep copy would need to be made -in AHat class >> you could access a[0] and resize any element and because they refer to the same element both would change

trees

-has one special element called a root that has children -these children can have children of their own -algorithms tend to involve starting at the top and walking to the bottom

Interface

-holds abstract method declarations -has a list of behaviors that objects know how to do -kind of like a category

break with switch statements

-if break isn't in the block, to will drop down to the next case -if you have the same outcome for multiple cases, don't put break ex: switch (digit){ case 0: case 4: case 5: case 9: mysteryValue=4; break;

keyword implements ex: public class Bird implements FlyingThing

-if it implements an interface, it has to know how to do everything listed in the interface -They have to know how to fly, takeOff, and land or else the code will not compile

Autounboxing

-if java needs an int and it needs an Integer object automatically does: int y= x.intValue( ); ex: Integer a; int z = a;

Autoboxing

-if java needs an integer object and it needs a primitive and wraps it automatically does: Integer x= Integer.valueOf(5); ex: Integer a; a=6;

what factors do we consider when choosing

-industry standard -ease of coding -efficiency -> runtime -> memory

What is are examples of software?

-internet browser -word processors -spreadsheet programs -operating system

graphs

-no special root -some vertices are connected to others by edges -Think of facebook -no special root

Draw Diagram: int[]a = new int[5]; int[]b = a; does this copy the array?

-no, makes them aliases

Big O of accessing ith element in a linked list

-nodes are not contiguously stored -you have to go node by node -have to traverse through the list O(n)

What cannot go in interface?

-nothing private -no instance variables- no state bc its not going to be an object -no constructor -no static variables that are not final

What can be in an interface?

-prototypes of public instance methods -public final static variables(have an assignment) -public static method implementations -public default instance methods

double x = 7.9; double y = x; String q = new String("Cat"); String r = q; String s = new String("Cat"); What is actually stored in the variable "q" in the previous question? Given the code fragment above, is it correct to say that "q is a String object"? Is it correct to say that "q refers to a String object"? Is it correct to say that "x is a double"? Is it correct to say that "x refers to a double"? How many String objects are actually created (instantiated) in the code fragment above?

-q holds the memory location corresponding to the place where the String "cat" is in RAM -You should NOT say "q is a String". You SHOULD say "q refers to a String". It is correct to say "x is a double", but you should NOT say "x refers to a double", since x is not a reference variable. -2 (new keyword)

Integer x= Integer.valueOf(5);

-static method in Integer class that wraps primitive into Integer object -there will only be one 5 on the heap, it is recycled

Do binary search recursively with helper method

...

Assume the following class definition (partially shown): public class Gorilla { public String name = "Frank"; public static int MAX_WEIGHT = 600; ...} Which of the following are valid expressions within a method that is outside of the Gorilla class? (Select all that apply.) ... Gorilla.name ... ... Gorilla.MAX_WEIGHT ... ... name ... ... MAX_WEIGHT ...

... Gorilla.MAX_WEIGHT ...

Assume the following class definition (partially shown): public class Gorilla { public String name = "Frank"; public static int MAX_WEIGHT = 600; ...} ... Gorilla.name ... ... MAX_WEIGHT ... ... name ... ... Gorilla.MAX_WEIGHT ...

... MAX_WEIGHT ... ... Gorilla.MAX_WEIGHT ...

public class Gorilla { public String name = "Frank"; public static int MAX_WEIGHT = 600; ...} Which of the following are valid expressions within an instance method of the Gorilla class? (Select all that apply.) ... Gorilla.name ... ... MAX_WEIGHT ... ... name ... ... Gorilla.MAX_WEIGHT ...

... MAX_WEIGHT ... ... name ... ... Gorilla.MAX_WEIGHT ...

Which of the following represent legitimate syntax for Java comments? (Select all that apply.) /* comment */ <!-- comment --> % comment # comment // comment

/* comment */ <!-- comment --> % comment # comment // comment

Practice using BOTH styles for Java comments.

//hi /** hi **/

What default values are used for instance and static variables?

0 for all primitive types (false for boolean, ASCII code 0 for char); "null" for reference variables

What default values are used for the variables mentioned above?

0 for all primitive types (false for boolean, ASCII code 0 for char); "null" for reference variables

Translate the hexidecimal (base 16) number 7F into binary representation.

01111111

How many parameters does the equals method have?

1

What is the value of the following Java expression: 37 / 4 * 4 % 3 + 1

1

How many bytes are in a megabyte?

1,000,000 or 2^20 bytes

What is the output of the following code fragment? (DO NOT WRITE ANY SPACES IN YOUR ANSWER. ALL OF THE OUTPUT WILL BE ON THE SAME LINE). for(int x = 17; x < 21; x = x + 3) { x = x - 1; System.out.print(x % 3); }

10

How many bytes are in a kilobyte?

1000 or 2^10 bytes

What is the base-10 number 39 in binary.

100111

What is the hexadecimal number F7 in binary.

11110111

After the following code has been executed, what is the value of the variable y? int x = 5, y = 10; if (x++ == 5 || --y >50) { y += 4; }

14

After the following code has been executed, how many objects have become "garbage"? Dog a = new Dog(); Dog b = new Dog(); b = a; a = new Dog(); a = new Dog();

2

int mystery (int w) { if (w < 0) return 0; int x = mystery (w - 2); return w - x; } What is returned by the call mystery(2)?

2

Translate the number 123 into base 7 representation

234 (base 7)

What is the output from the following code fragment? (The output will all be on the same line. Do not include any spaces in your answer.) int x = 0; while (x < 16) { x += 2; if (x > 8) { break; } if (x % 3 < 2) { continue; } System.out.println(x); }

28

How many different combinations of 0's and 1's can be represented using 7 bits?

2^7 =128

How many Dog objects are created by the following code fragment? Dog a = new Dog("Spot"), c = new Dog("Alfie"); Dog b; Dog d = a; Dog f = new Dog(a);

3

What is the value of the following Java expression: 33 % 5

3

int mystery (int w) { if (w < 0) return 0; int x = mystery (w - 2); return w - x; } What is returned by the call mystery(5)?

3

How many different values can be represented by 5 bits?

32

What is the output from the following code fragment? (Note that the output will all be on the same line.) for (int i = 2; i < 10; i++) { if (i % 2 == 0) { continue; } if (i > 8) { break; } System.out.print(i); }

357

What is the output of the following code fragment? (DO NOT WRITE ANY SPACES IN YOUR ANSWER. ALL OF THE OUTPUT WILL BE ON THE SAME LINE). for (int x = 7; x < 11; x = x * 2) { x -= 3; System.out.print(x); }

457

Evaluate the following Java expression: 75 % 7

5

Evaluate the following Java expression: 9 - 15 * 6 / 11 + 4

5

What does this print? for(int i=1; i<10; i++){ if(i < 5) { continue; } System.out.println(i); if(i > 7){ break; } } System.out.println("out");

5 6 7 8 out

How many ints are created by the statement: int[] a = new int[5];

5, all 0

Assuming that x is a positive integer, what is the largest value that that the following expression could be? x % 7

6

After the following code has executed, what is the value of y? int x = 7, y = 8; if (x < 4 && y++ != 100) { y += 3; }

8

How many bytes of memory are required to store each type of variable? double int short char long

8,4,2,2,8

Translate the binary (base 2) number 1011010 into base 10 representation

90

List the following operators in order of precedence (highest precedence first, lowest precedence last). || < += && ==

< == && || +=

public class Nonsense { public static void foo(int x) { if (x == 2) { throw new NullPointerException( ); } else if (x == 3) { throw new NumberFormatException( ); } System.out.println("A"); } public static void main(String[] args) { for (int i = 1; i <= 3; i++) { try { foo(i); System.out.println("B"); } catch (NullPointerException e) { System.out.println("C"); } finally { System.out.println("D"); } System.out.println("E"); } System.out.println("F"); } }

A B D E C D E D

@Override

A Java annotation used to indicate that a method is intended to override an inherited method. -has to have the EXACT same prototype

Define the term "bit".

A binary digit, either 0 or 1.

Aliasing

A circumstance where two or more variables refer to the same object.

sub class

A derived class that inherits features from another class

Formal Verification

A field of computer science that involves reasoning about the formal properties of programs to prove the correctness of a program.

What is a "setter"?

A method that modifies the value of an instance variable of the object.

What is a getter

A method that returns the value of an instance variable of the object.

is a

A phrase to say that something inherits from another, as in a "salmon" is-a "fish."

Stack

A stack is a simple linear data type in which elements are both inserted ("pushed") and removed ("popped") from the same end. (We usually picture the stack vertically, and say that we "push" and "pop" items from the top.)

local variable

A variable with local scope is one that can only be seen, used and updated by code within the same scope. Typically this means the variable was declared (created) inside method

Big O Notation

A way of expressing the worst-case run-time of an algorithm

Rules for identifiers

A-Z, a-z, 0-9, $, _, cannot begin w a digit, cannot use any known identifiers

This definition pertains to the first three questions: Assume there is a class called IntegerMath that contains a static method called getSqrt with the prototype below. Normally this method returns the positive square root of the parameter, x, however: if x is negative, it throws an ArithmeticException. If the square root of x is not an integer, then it throws an IllegalArgumentException. In other words, if the argument is 16, it returns 4. But if the argument is 15, it throws the IllegalArgumentException, because the square root of 15 is not an integer. public static int getSqrt(int x) What is the output of the program below? (The output will all be on one line. Do not type spaces in your answer.) public static int calculate(int y) { int answer = 9; try { answer = IntegerMath.getSqrt(y + 3); } catch(ArithmeticException e) { System.out.print("A"); } finally { System.out.print("B"); } System.out.print("C"); return answer; } public static void main(String[] args) { try { int result = calculate(-5); System.out.print(result); } catch(ArithmeticException e) { System.out.print("D"); } catch(IllegalArgumentException e { System.out.print("E"); } System.out.print("F"); }

ABC9F

example of deep copy

AdjustableHat[] copy = new AdjustableHat[myHats.length]; for (int i = 0; i < myHats.length; i++) { copy [i] = new AdjustableHat(myHats[i]) ; } return copy;

Values

All literals carry values (ex: x, 17, x*y)

semantic error

An error in a program that makes it do something other than what the programmer intended.

Run-Time Error

An error in a program that makes it impossible to run to completion. Also called an "exception".

FlyingThing[ ] things= new FlyingThing[3]; What can you put in here?

Any type of FlyingThing things[0]= new Bird( ); things[1]= new UFO( ); things[2]= new Airplane( );

API

Application Programming Interface

ArrayList syntax- making an array of cat objects

ArrayList <Cat> a = new ArrayList<Cat>( );

This definition pertains to the first three questions: Assume there is a class called IntegerMath that contains a static method called getSqrt with the prototype below. Normally this method returns the positive square root of the parameter, x, however: if x is negative, it throws an ArithmeticException. If the square root of x is not an integer, then it throws an IllegalArgumentException. In other words, if the argument is 16, it returns 4. But if the argument is 15, it throws the IllegalArgumentException, because the square root of 15 is not an integer. public static int getSqrt(int x) What is the output of the program below? (The output will all be on one line. Do not type spaces in your answer.) public static int calculate(int y) { int answer = 9; try { answer = IntegerMath.getSqrt(y + 3); } catch(ArithmeticException e) { System.out.print("A"); } finally { System.out.print("B"); } System.out.print("C"); return answer; } public static void main(String[] args) { try { int result = calculate(1); System.out.print(result); } catch(ArithmeticException e) { System.out.print("D"); } catch(IllegalArgumentException e { System.out.print("E"); } System.out.print("F"); }

BC2F

This definition pertains to the first three questions: Assume there is a class called IntegerMath that contains a static method called getSqrt with the prototype below. Normally this method returns the positive square root of the parameter, x, however: if x is negative, it throws an ArithmeticException. If the square root of x is not an integer, then it throws an IllegalArgumentException. In other words, if the argument is 16, it returns 4. But if the argument is 15, it throws the IllegalArgumentException, because the square root of 15 is not an integer. public static int getSqrt(int x) What is the output of the program below? (The output will all be on one line. Do not type spaces in your answer.) public static int calculate(int y) { int answer = 9; try { answer = IntegerMath.getSqrt(y + 3); } catch(ArithmeticException e) { System.out.print("A"); } finally { System.out.print("B"); } System.out.print("C"); return answer; } public static void main(String[] args) { try { int result = calculate(7); System.out.print(result); } catch(ArithmeticException e) { System.out.print("D"); } catch(IllegalArgumentException e { System.out.print("E"); } System.out.print("F"); }

BEF

Write the hexadecimal representation of the binary number 11000100

C4

FlyingObject x; x.destroyPlanet( );

CANNOT DO -You do not know what FlyingThing is, therefore destroyPlanet may not be part of that class -destroyPlanet was only in the UFO class

Does the getter in the Basket class, below, cause a privacy leak? public class Basket { private Egg[] eggs; ... public getEggs( ) { Egg[] copy = new Egg[eggs.length]; for (int i = 0; i < eggs.length; i++) { copy[i] = eggs[i]; } return copy; } ... }

Cannot decide without more information- depends on mutability

class Main { public static void main(String[] args) { int expression = 2; // switch statement to check size switch (expression) { case 1: System.out.println("Case 1"); // matching case case 2: System.out.println("Case 2"); case 3: System.out.println("Case 3"); default: System.out.println("Default case"); } } }

Case2 Case3 Default Case

int num=0; switch(num+2) { case 1: System.out.println("Case1: Value is: "+num); case 2: System.out.println("Case2: Value is: "+num); case 3: System.out.println("Case3: Value is: "+num); default: System.out.println("Default: Value is: "+num); } }

Case2: Value is: 0 Case3: Value is: 0 Default: Value is: 0

Describe how a break statement behaves

Causes the inner-most loop or switch statement to be exited immediately.

What does CPU stand for?

Central Processing Unit

x=1782345433426L; y= (int) x; System.out.print(y);

Chops off numbers to fit size and twos compliment

Typical static method call

Class.method( );

What programming language was used in the business world in the 1950's

Cobol

Pirate x = new pirate( ); Pirate y = new Pirate(x);

Copy constructor defines whether it is deep or shallow

shallow copy

Copying only the reference to an object.

If you want the Handler to make the user re-input

Do-While Loop

If this is the constructor: Dog(String name, double weight, int numCars){ this.name = name; } How do you make a constructor using the this keyword that constructs a Dog that never chases any dogs?

Dog(String name, double weight){ this(name, weight, 0) }

Where can you use a "break" statement?

Either in a switch statement or in a loop.

Linear data type

Elements are listed in a row or a sequence (does not have to be sorted) - an array is an example of this

Explain why it is important to limit the number of public members.

Encapsulation of the fields (instance variables) of a class is very important. We frequently need to make changes to a class. If these changes do not modify the class API, then the modified class will work perfectly well within an existing project. However, if you modify the class in such a way that the API is changed, then you will have to re-program other components of the project so that they will work with the new class. By limiting the API we are free to make more extensive changes to the class without having to re-program other parts of the project.

Explain what is happening here and a faster way to do this. Integer a, b, x; x= Integer.valueOf(a.intValue( ) + b.intValue( ));

Explain: a and b are converted to primitive ints and added, and then wrapped into an integer object and assigned to x Faster: x= a + b; Integers are unboxed and added, and then boxed to be assigned to variable x

Explain what is happening here and a faster way to do this. Integer a, b, x; if (a. compareTo(b) < 0)

Explain: compareTo is part of the Integer class so this will work Faster: if(a<b) a and b are unboxed and compared when java sees the less than symbol

(True/False) The following method always prints "YES", as long as the arguments are positive values: public static void foo(double a, double b) { if (a + b - a == b) { System.out.println("YES"); } }

FALSE

TRUE/FALSE: Inserting unnecessary spaces and/or blank lines could cause your Java program to malfunction.

FALSE

(True/False) If a run-time error occurs during a particular JUnit test then the rest of the tests will still be attempted.

False

(True/False) The following code fragment will compile: int y = 5; if (y < 10) { int x = 17; } System.out.println(x);

False

(True/False). JUnit tests are always executed in the order in which they appear in the test suite.

False

(True/False). Suppose a single JUnit test contains multiple assertions. If the first assertion fails, JUnit will continue running the test to see whether the subsequent assertions in the test will pass or fail.

False

True/False --Aliasing can lead to problems if the object is immutable.

False

True/False: An instance variable can be declared as "static".

False

True/False: In order to run a static method, you must run it for a particular object (the current object).

False

(True/False) The following could appear in an interface: public void h(int b) { System.out.println(b); }

False- not a default instance method

True/False) The following could appear in an interface: public static int x;

False- not final

Consider the assignment statement: x = y; If the variables are of type "int", does the integer get copied? If the variables are of type "String", does the String get copied?

For primitive types (like int), the data is copied. For reference variables (like a String reference), the memory locations are copied, NOT the objects themselves.

What programming language was used by Scientists and Engineers in the 1950's?

Fortran

Describe how a continue statement behaves in a while loop.

Goes to top of loop immediately and checks the boolean condition to see if looping should continue.

Which of the following are considered "secondary memory devices". (Select all that apply.) RAM Hard drive USB flash drive Touchscreen monitor

Hard drive USB flash drive

Give some examples of secondary memory devices

Hard drives, floppy disks, flash memory devices, CD's , DVD's

When writing getters

If there are private members, preserve encapsulation >> if mutable, make copies before returning a reference in your getters ex: public Parrot getParrot( ){ // mutable!! return newParrot(bird); }

garbage collector

In a managed memory system, the program that periodically runs to free unreferenced memory

add(int index, E element)

Inserts the specified element at the specified position in this list.

Where can you use a "continue" statement?

Inside of any loop.

What does IDE stand for?

Integrated Development Environment

What happens when this runs? public static void doFlight(FlyingThing flyer){ flyer.takeOff( ); }

It depends! If flyer is a bird- will do bird takeOff method If flyer is a UFO- will do UFO takeOff method If flyer is a plane- will do plane takeOff method

Dog x = new Dog("Spot"); // Spot is assigned as the Dog's name foo(x); After the call to foo(), will the Dog's name still be "Spot"?

It is impossible to know without seeing the code for the method foo

public static void g(int[] a) { a[0] = 4; foo(a); } After the call to the foo method is over, will the first element of the array still be set to 4?

It is impossible to know without seeing the code for the method foo

Describe how a continue statement works in a for-loop.

It will execute the statement that is usually processed at the end of an iteration through the loop, and then check the boolean condition to see if looping should continue.

We want to write a method called "checkAddition" that accepts as parameters two double values, x and y, and a third value, total. The method should return true if total is the sum of x and y, and false otherwise. Consider this potential implementation: public static boolean checkAddition(double x, double y, double total) { return x + y == total; } Assume that the arguments to the method will always be values in the range from 0 to 1000, and that the arguments, when written in base-10 notation, will never have more than 5 digits after the decimal point. Will this implementation return the correct value under these assumptions?

It will sometimes produce the correct result and sometimes not- only if it is able to be represented in base 2

Let's say an Exception is thrown at H (which is called by previous methods: G, F, Main)

Java will look for an Exception Handler in H. If there's no exception in H it will Pop the H Method off the stack, making sure no code within H is executed Java will then look for an Exception Handler in G. If there's no exception in G it will Pop the G Method off the stack, making sure no code within G is executed Java will then look for an Exception Handler in F. If there's no exception in F it will Pop the F Method off the stack, making sure no code within F is executed Java will then look for an Exception Handler in Main. If there's no exception in Main it will Pop the Main Method off the stack, making sure no code within Main is executed and the whole program is terminated >> which is when you get the red error message in the Console

Input device examples

Keyboard, mouse, speaker, touchscreen, storage device, scanner, microphone

generally, is the line or parabola favored?

Line, but only in large sets

What programming language was developed in the 1950's and is still used in A.I.?

Lisp

If someone showed you a Java class, how can you quickly identify which members were part of the API for that class?

Look for "public" members.

Output device examples

Monitor, printer, storage device, speakers, projector

Which of the following are advantages that secondary memory has over RAM? (Select all that apply.) More permanent (non-volatile) Faster Typically has more storage space

More permanent (non-volatile) Typically has more storage space

Aliasing becomes a problem for

Mutable Objects

If a member is declared as private, can it be accessed from another class?

N

Are Integer objects mutable? (If you're not sure, inspect the online API documentation for the Integer class and find out!)

NO

Suppose you are passing (or returning) an array of primitives to/from a method. Is it safe to make a reference copy only?

NO

Can you do: FlyingObject x; x= new FlyingObject( );

NO! FlyingObject is an interface, not a class. Therefore, you cannot instantiate it. You do not know what kind of FlyingObject it is.

Suppose you are passing or returning an array of references to mutable objects to/from a method. Is it safe to make a reference copy only? Is it safe to make a shallow copy?

NO, NO

Suppose you are passing (or returning) an array of references to immutable objects to/from a method. Is it safe to make a reference copy only? Is it safe to make a shallow copy?

NO, YES

What if destroyPlanet( ) was a method in all of the classes but not in the interface FlyingThing? Would you then be able to use it?

NO, it's not in the interface therefore it is not one of the behaviors that are possible of a FlyingThing

Can you do: Integer x= new Integer(5);

NO- if you needed 18 5's, you would have 18 different copies of an immutable object 5 which is unnecessary do: Integer x= Integer.valueOf(5);

Can you find when the linear and parabolic algorithms will meet and be equal in runtime?

NO- depends on too many factors

public static void foo( ){ Dog x= new Dog( ); Dog.weight( );

NO- for static members only, which dog is it? weight instance variable is inside each dog

public void bark( ){ Dog x= new Dog( ); Dog.weight

NO- for static members only, which dog is it? weight instance variable is inside each dog

public static void foo( ){ Dog x= new Dog( ); ...weight...

NO- no current object

Could the following pair of methods be included in the same class? public void f(int x) {...} private int f(int y) {...}

No

is the processing always proportional to the size of the data set?

No

How many Strings are created by the statement: String[] a = new String[5]; (Hint: The answer to this question and the previous question are different!)

None! (Just 5 null references are created -- no objects are instantiated).

What is accomplished when you type "import java.awt.Color;" at the top of a file?

Now whenever you type "Color", the compiler knows that you are talking about the Color class that resides in the package called "java.awt".

Fastest big o category

O(1)

Big O of binary search

O(log n) Actually log2n but this goes into the category log n

Binary Search Big O

O(log2n)

Big O for Linear search

O(n)

Linear Search Big O

O(n) because in the worst case, you have to go through every element -Straight line

Big O of does a list of size n contain duplicates?

O(n^2)

big O of coloring every square in a flag of height n by width 2n

O(n^2) You have to go through every box Actually 2n^2 but this goes into the category n^2

Mutable Objects:

Once the object has been constructed, you can change the state of the object

Which of the following could be cases in a switch statement where the variable at the top is type int? (Select all that apply.) case foo(): // assume foo() returns type int case x: // assume x is an int variable case 4: case x<5:

Only case 4, has to be a constant expression but could work if x was a final int variable

What programming language was used primarily for education in the late 80's

Pascal

FlyingObject x; x= new Bird ( ); x= new Airplane( ); x= new UFO( );

Polymorphic variable -can be assigned any object that implements the FlyingObject interface

Wrapper classes

Replaces the API of the inner member with the API of the outer class

contains(Object o)

Returns true if list contains specified element

What programming language claims to be based on "the principal of least astonishment"?

Ruby

Binary Search Algorithm

Start in the middle and eliminate half the stack and keep looking in the middle. The data is pre-sorted. The process of examining a middle value of a sorted array to see which half contains the value in question and halving until the value is located.

instance variables

Storage for data in an instance of a class/ object---- for the state of the object - each object has its own copy of the variables

Write some faulty code that generates a null-pointer exception, catch the exception immediately and print out "exception caught" in your catch block.

String s = null; try { int x = s.length( ); // throws exception } catch (NullPointerException e) { System.out.println("exception caught"); }

In the code fragment below, which of the following types could the variable x be? (Select all that apply.) switch(x) {...} String int short byte long char

String, int, short, byte, char

What is the difference between System.out.print and System.out.println?

System.out.print just prints everything in a line System.out.println moves the cursor down to the next line after it does it's output.

public class Pumpkin { public static int x; public int y; ... } Which of the following statements will compile and run successfully in a static method of the Pumpkin class? System.out.println(Pumpkin.y); System.out.println(y); System.out.println(x); System.out.println(Pumpkin.x);

System.out.println(Pumpkin.y); System.out.println(y); System.out.println(x); System.out.println(Pumpkin.x);

public class Pumpkin { public static int x; public int y;... } Which of the following statements will compile and run successfully in an instance method of the Pumpkin class? System.out.println(y); Sytem.out.println(Pumpkin.y); System.out.println(x); System.out.println(Pumpkin.x);

System.out.println(y); Sytem.out.println(Pumpkin.y); System.out.println(x); System.out.println(Pumpkin.x);

If you change a class in such a way that the API changes, then other classes which depend on this one will have to be re-coded.

TRUE

The assignment operator

The '=' character causes the compiler or interpreter to evaluate to the expression on its right and store the result in the variable(s) on its left.

method overloading

The ability to define two or more different methods with the same name in the same class with different parameters

short circuiting

The computer looks at the first statement and uses that information to decide if it needs to look at the rest of the statement.

heap

The heap is the region in memory where Objects are stored. When objects are no longer being used, that memory is "recycled" automatically so that it can be used by other Objects later.

Command Line

The place where typed commands are given to the operating system

rewrite this using the ternary operator: if(MODE == slow){ Thread.sleep(1000); }else{ Thread.sleep(100); }

Thread.sleep((MODE==slow)? 1000 :100);

Big O counting enemies on n by n battlefield

To find the enemies, u have to go through the whole grid O(n^2)

pop

To remove an item from the top of a stack.

(True/False) A class can implement more than one interface.

True

(True/False) Multiple classes can implement the same interface.

True

True or False: There are always categories betweeen.

True

True/False -- Aliasing can lead to problems if the object is mutable.

True

True/False: In order to run an instance method, you must run it for a particular object (the current object).

True

True/False: The same class can contain some members that are static and some members that are non-static.

True

(True/False) The following could appear in an interface: public static void g(String a) { System.out.println(a); }

True- normal static method implementation

To compile java source code

Type javac and then the name of the file including the extension .java

when to use switch statement

When there is a variable and the value of that variable dictates choices

Big O inserting at the front of an array

Work is in copying stuff into the array that is 1 bigger O(n)

void f(int x, double y) void f(double x, int y)

Works, but method calls could be ambiguous. For example: f(2, 3)will not compile.

ternary operator X? Y : Z What is X?

X must be a boolean expression

If a member is declared as private, can it be accessed from inside the same class?

Y

If a member is declared as public, can it be accessed from another class?

Y

If a member is declared as public, can it be accessed from inside the same class?

Y

If a member is declared as public, can it be accessed from inside the same class? If a member is declared as public, can it be accessed from another class? If a member is declared as private, can it be accessed from inside the same class? If a member is declared as private, can it be accessed from another class?

YES YES YES No

public void bark( ){ Dog x= new Dog( ); .... x.weight( )....

YES- accessing instance variable using an object

public static void foo( ){ Dog x= new Dog( ); x.weight( );

YES- called upon object

public void bark( ){ Dog x= new Dog( ); ....weight.....

YES- represents the weight of the dog that is barking right now

public void bark( ){ Dog x= new Dog( ); Dog.MIN_DOG_WEIGHT

YES- typical syntax, used in other classes besides Dog class

public void bark( ){ Dog x= new Dog( ); x.MIN_DOG_WEIGHT

YES- will access the min dog weight through x but not used often

public void bark( ){ Dog x= new Dog( ); MIN_DOG_WEIGHT

YES- works as long as you are in Dog class

Consider the following code fragment: int x = 17; foo(x); System.out.println(x); Will the output be 17?

Yes

Does the getter in the Basket class, below, cause a privacy leak? public class Basket { private Egg[] eggs; ... public getEggs() { return eggs; } ... }

Yes

Are the elements of an array of primitives automatically initialized? If so, to what values?

Yes, 0

Could the following pair of methods be included in the same class? public void f(int x, String y) {...} public void f(String y, int x) {...}

Yes, and there is no possibility of ambiguous method calls

public void f(int x) {...} public void f(long x) {...}

Yes, and there is no possibility of ambiguous method calls

Could the following pair of methods be included in the same class? public void f(short x, long y) {...} public void f(long x, short y) {...}

Yes, but there is a possibility of ambiguous method calls

Could you put int x=3; in an interface?

Yes, it is seen as public static final int x=3;

Will this work? public void foo(int x) public void foo(long y)

Yes- if the first method did not exist and you passed in 5, it would still run and the 5 would be casted to a long >>> the method runs that is "closest" to the type of variable that you enter

Will this work? public void foo(int x, String y) public void foo(String x, int y)

Yes- Order matters!

What is accomplished when you type "import java.awt.*;" at the top of a file?

You are importing EVERYTHING that is in the package java.awt.

Picture a parent class Clock that has subclass alarmClock that has subclass radioAlarmClock. What can you pass into this method? What methods can you call on c? void moveForwardOneHour(Clock c)

You can pass anything that is a clokc into the method. However, you can only call methods that are in the clock method on c.

Picture a parent class Clock that has subclass alarmClock that has subclasses radioAlarmClock and natureClock. What can you pass into this method? What methods can you call on c? void soundAlarm(AlarmClock c)

You can pass in any class that is an alarmClock. You can call any Clock aand alarmClock methods.

Quotation mark

\"

one slash

\\

new line

\n

tab

\t

Assume that the following code has been executed. String a = new String("bozo"); String b = a; String c = new String(b); Which of the following boolean expressions will evaluate as true? (Select all that apply.) b == c a == b a.equals(c)

a == b a.equals(c)

copy constructor

a constructor that accepts an object of the same class as an argument

What is assembly language?

a mnemonic representation of machine language

instance variable

a variable defined in a class for which every object of the class has its own value

What term describes the situation where two different variables refer to the same object? (Your answer should be one word.)

alias

Which of the following should be described in the comment that appears directly above a method? (Select all that apply.) Side effects that result from calling the method (assuming there are side effects) Acceptable values for the parameters (assuming there are parameters) Description of how the return value is calculated (assuming there is a return value)

all of the above

Whats better about extending a class?

allows inheritance of all methods and all variables- heavy decision

Cases must

always be constant expressions (cannot be x or call a method) UNLESS IT IS FINAL!

The "try" block is

always executed

FlyingObject x; What can be assigned to x?

an instance of any class that implements the FlyingThing interface

Deep copy

an operation that not only copies one class object to another but also makes copies of any pointed-to data

Linear Algorithm

any straight line graph

stringBuffer.append()

appends the arguments to the StringBuffer- much faster in loops

Assume that the variable arr represents a ragged 2D array. Write an expression whose value is the number of rows in the 2D array. (Do not include any spaces or extra symbols in your answer).

arr.length

Assume that the variable arr represents a ragged 2D array. Write an expression whose value is the length of the first row in the array. (Do not include any spaces or extra symbols in your answer).

arr[0].length

void arrayTraverse (int current, int[ ] array){ if (current == array.length)return; // process array[current] arrayTraverse ( _________, array); } How should arrayTraverse be called to process every element in the array nums?

arrayTraverse(0,nums)

Two different data structures for linear abstract data type

arrays(and arrayList), Linked allocation

what does this subject have to do with asymptotes?

as n gets bigger, function gets closer and closer to an asymptote

Why exceptions are better

because the user might be confused since they don't read the instructions. Additionally, the Error Code might be processed like normal data

Beginning of linked list name and end of linked list

beginning: head end: null reference

Write a statement that simultaneously declares three variables of type boolean, named x, y, and z.

boolean x, y, z;

Shoe analogy- if two objects are aliases and one of them is mutable

both objects will change

Which of the following will compile? (Select all that apply.) byte a = 17; byte d = 130; double c = 15F; String e = 'x'; int b = 15L;

byte a = 17; NOT BYTE D BECAUSE IT CAN ONLY STORE UP TO 127 double c = 15F;

When your Java program is compiled, what type of file is created? (Hint: It is NOT machine language.)

bytecode

What does it mean for someone to say that a Java program is "portable"?

bytecode will run successfully on any platform as long as java virtual machine is available

this and constructors

call constructors from different constructors

instance variables drawing

call stack holds reference to memory location of obj, where any new instance variables are made, primitives stay in that obj and new obj (Strings, names) are made with a new reference

Immutable Objects

cannot be changed after initialized by constructor

List the two Java primitive types that are used to store values that are not numbers.

char boolean

Which of the following represents the correct way to declare three char variables at the same time? char a, char b, char c; char a char b char c; char a b c; char a, b, c;

char a, b, c;

Initializing An Array When Constructed

char[] array = {'q', 't', 's', 'r'} Cat [] kitties = {new Cat ("Felix"), new Cat ("Tom"), new Cat ("Sylvia"), new Cat ("Steve")}

What will the output be? int x = 4; if (x < 7) { int y = 9; } else if (x < 8) { int y = 15; } System.out.print(y);

code fragment won't compile

How is your Java source code translated into machine code?

complier > interpreter

ternary operator

condition ? value if true : value if false;

Where can the keyword "this" be used?

constructors, instance methods

Concatenation doesn't modify the string, it

creates a new string with the modification and assigns it to the original variable

void arrayTraverse (int current, int[ ] array){ if (current == array.length) return; // process array[current] arrayTraverse ( _________, array); } The method arrayTraverse recursively visits each element in an array, processing each element in some way. Which expression should go in the blank?

current + 1

state

data contained inside object

Consider the class below (partially shown): public class MyWords { private StringBuffer[] words; ...} If you are writing a "getter" for the variable "words", what should the return value refer to?

deep copy

this.patch= new eyepatch(other.patch);

deep copy constructor- invoking the copy constructor of the eyepatch class

I/O device

devices that allow you to communicate with the computer

Write a method with the prototype shown below. The return value will be an exact copy of the parameter, but each value from the parameter will be represented twice. For example, if the parameter is the array [2, 5, 9] then the return value will be the array [2, 2, 5, 5, 9, 9]

do in eclipse

Write a method with the prototype shown below. The return value will be an exact copy of the parameter, but with the even numbers removed. For example, if the parameter is the array [7, 4, 19, 8, 11] then the return value will be [7, 19, 11].

do in eclipse

implicit casting hierarchy

double float long int short byte

What IDE will we use in class this semester?

eclipse

cons of formal verification

expensive, time consuming

when does the base matter? (exponential vs. logarithmic)

exponential 72^n vs 2^n log2n = log72n

(True/False) If a class implements an interface, the only methods that may be present in the class are those that are listed in the interface.

false

(True/False) If a method is not correct, testing is more likely to demonstrate the failure than "formal verification".

false

(True/False) The following code fragment will compile: int x; if (x == 6) { System.out.println("Hi"); }

false

(True/False) The following could appear in an interface: public static int x;

false

(True/False) The following could appear in an interface: public void greenCorner(MyGrid grid) { grid.setColor(0, 0, Color.GREEN); }

false

(True/False) The following two loops behave the same way in all cases: while(x < 0) {...} __________________________________________________________ do { ...} while(x < 0);

false

(True/False) These two expressions carry the same value: (Assume that in both expressions, x starts with the same value). --x ++x

false

If you change a class without modifying the API, then other classes which depend on this one will have to be re-coded.

false

True or false: There is a slowest big o category.

false

Which of the following are advantages that RAM has over secondary memory?

faster

StringBuffer being mutable is good because

faster and uses less memory

indexOf(Object o)

finds object index

List the two Java primitive types that can be used to store floating point values.

float double

How much memory is required to store float and double

float - 4 bytes double - 8 bytes

Assume there is a class called Apple, which is inside a package called fruit. The fruit package is inside a package called food. What is the fully qualified name of the Apple class?

food.fruit.Apple

for-each loop

for (Type variable: collection){ Statement } -first time through the loop, variable refers to first element in the collection -pattern repeats -variable has to be the same type s the collection holds

iterating through ragged array

for (int row = 0; row < name.length; row++) { for (int col = 0; col < nam[rows]e.length; col++) { Process name[rows][cols]; } }

After you have created this array, write code that will print the contents in the same format that you see above. 5 8 9 4 11 13 15 17 0 1

for (int row = 0; row < x.length; row++) { for (int col = 0; col < x[row].length; col++) { System.out.print(x[row][col] + " "); } System.out.println(); }

looping through 2d array with for each loops

for(int[ ] row: arrayName) for(int col: row) -the type of each row is an int [ ] array -for the inner loop, each column is an int, in the current collection row

Each primitive type in Java

has a corresponding wrapper class

if mixture of mutable and immutable

hybrid: age=other.age; weight=other.weight; patch=other.patch; bird=new parrot(other.bird);

When to use shallow copy

if immutable

using instance variables

if in the same class- variable; if in different class- obj.variable;

O(n)

if it is linear (or faster) -can be used to discuss an actual function or an algorithm if it has a straight line graph

O(log n)

if it is logarithmic (or faster)

O(n^2)

if it is quadratic or faster

When to use deep copy

if mutable

Use array list when

if things may be added or removed

Under what circumstances will Java provide a default constructor for you automatically?

if u dont write one

When passing variables into functions as parameters

if variables are primitives- values do not change during a method call if variables are objects- method can change the state of the objects

when to use linear search

if you have no knowledge about the organization of the list

The string class is immutable/mutable

immutable

Strings are

immutable- cannot be changed

Assume there is a class called Carrot that is inside a package called veggies. If you are writing a class that is outside of the veggies package, what statement would you write at the top of your class so that you could declare variables of type Carrot without using the fully qualified name?

import veggies.Carrot;

Assume there is a class called Car that is inside a package called vehicles. If you are writing a class that is outside of the vehicles package, what statement would you write at the top of your class so that you could declare variables of type Car without using the fully qualified name?

import vehicles.Car;

what happens to the runtime when the data set doubles? -- logarithmic algorithm

increases by a fixed constant

Which kinds of variables are given default values if you do not initialize them? (Local/ instance/static? Which ones?)

instance and static

behaviors of objects

instance methods

In which of the following places does it make sense to use the Java keyword "this"?

instance methods & constructors

state of objects

instance variables

How much memory is required to store : int byte short long char

int - 4 bytes byte - 1 byte short - 2 bytes long - 8 bytes char - 2 bytes

Write a statement that declares a variable named counter of type int, and stores the value 182 in the variable.

int counter = 182;

Which of the following will compile? (Select all that apply.) int u = (int) 999999999999L; float t = 3.4; double r = 7; long v = 999999999999; long s = 24F;

int u = (int) 999999999999L; double r = 7;

Below are examples of declaring an instance variable, x. The first example uses public visibility. The second examples uses private visibility. public int x; private int x; What statement would you write to declare x with package visibility?

int x;

int[] x, y; int a, b; can also be written as

int x[], y[], a, b; BUT NOT RECCOMMENDED

What variables can be at the top of the switch statement?

int, short, byte, char, String NOT LONG

Write a legitimate Java statement that will declare a variable called values, that will represent an array of ints. Your statement should also simultaneously assign to the variable an array of size 100.

int[ ] values= new int[100];

Write a code fragment that creates a two-dimensional ragged array of ints with 3 rows, initialized with the following data: 5 8 9 4 11 13 15 17 0 1

int[][] x = {{5, 8, 9}, {4, 11, 13, 15, 17}, {0, 1}};

To resize an array

int[]a = new int[5]; int[] b= new int (a.length + 1); -Then use a loop to assign every value in array a to array b -Access the last box (a.length - 1) and assign it a value -Then alias the original array to the new array

Objects are constructed using "new" which

invokes a constructor

StringBuffer

is mutable

If one person has a linear algorithm and someone else has a quadratic algorithm which will run faster?

it depends- picture a linear that is very steep and a very gradual parabola - in smaller sets of data, it depends -in larger sets of n, the parabola will be slower because it does not have a fixed slope, versus the linear graph has a fixed slope -as n goes towards infinity, the parabola is worse than the straight line

To invoke the java virtual machine to run the byte code

java followed by the name of the class that has the main method without .class on the end of it ex: java HelloWorld

Which java package is automatically imported in its entirety into every Java program you write?

java.lang

What package is the Scanner class located in? What is the fully qualified name of the Scanner class?

java.util is the package. The fully qualified name is "java.util.Scanner"

Assume you have an array called list. What expression will return the number of elements in this array? (Be sure to write correct Java syntax.)

list.length

What do you call the language that the CPU uses (0's and 1's represent instructions in this language)

machine language

when you make a 2d array, what step do you have to do

make the references to each array in each row ex: int [ ] [ ] a= new int [4] [ ]; a[0] = new int[4]; a[1]= new int[2]; a[2]= new int [1]; a[3]= new int[4];

What term describes 2^20 bytes of space?

megabyte

package visibility

member is visible in class and any class in the same package

When objects are passed as parameters

memory location gets copied (think memory diagram)- arrows point to same as in main method

FINALLY BLOCK- an exception is thrown and the handler isn't found locally

method is popped off the stack > finally block

calling another instance method in same class

method( ) ;

Calling static method in same class

method( );

What advantage do you gain from using one of the floating point types that requires MORE memory?

more precision (retains more digits)

What is the advantage of primary memory over secondary?

much faster

What is the advantage of secondary memory over primary?

much more storage and it is permanent

arrays are always (draw diagram of a reference array)

mutable so if there is an alias to an array you can change any of the elements in the array

2D array- To return the length of name[ ][ ] (how many rows)

name.length

2D array- To return the length of a row in name[ ][ ] (how many cols in that row)

name[row num].length

Are integers or primitives effected by either shallow or deep copies?

no

Can you have multiple try blocks for one catch block?

no

Is the following statement valid: int x = 34.7;

no

Will this work? public void foo(int y) public int foo(int x)

no

Will this work? public void foo(int y) public void foo(int x)

no

punctuation in javadoc

no

int x=17; byte c=x; works or no

no bc hierarchy but if you do byte c= 17 it will compile

Dog a, b, c;

no dog obj made until NEW keyword

If there's a return statement IN A CATCH BLOCK

no other code afterward is run EXCEPT the finally block

As soon as the exception is thrown in a specific method,

no other code within that method is executed

is there a best data type?

no, based on scenario

If there's an exception early on within the try block,

none of the statements after that are attempted because the program is looking for Exception Handlers. Once the Exception is Handled, none of the remaining code within the try block is executed

Pirate x = new pirate( ); Pirate y = x;

not a copy, aliasing

2d ragged array

not all rows are the same size

alarmClock extends Clock

now alarmClock has all of the features of Clock- all instance variables, constructors, methods

Typical instance method call

object.method( );

private

only available in class

unary operator

operator with only one operand( ++, --, !, -(negative sign), +(positive sign))

if a class is inside of a named package, what appears at the top?

package packageName;

Assume there is a class called Carrot in a package called veggies. What statement must appear at the top of the Carrot class (since it is in the veggies package)?

package veggies;

Assume there is a class called Car in a package called vehicles. What statement must appear at the top of the Car class (since it is in the vehicles package)?

package vehicles;

If you were taking an introductory programming course in the 1980's, which of language is most likely to have been taught?

pascal

rewrite this using the ternary operator: if(shape== CIRCLE) { perimeter = Math.PI * size; }else { perimeter = 4 * size; }

perimeter= ((shape==CIRCLE)? Math.PI * size: 4*size);

example of shallow copy

public AdjustableHat[] getHatsTwo() { AdjustableHat[] copy = new AdjustableHat[myHats.length]; for (int i = 0; i < myHats.length; i++) { copy [i] = myHats[i]; } return copy; }

correct equals method w/ clock example instance variables = hours, mins, secs

public boolean equals(Object x){ if( !(x instanceOf Clock){ return false; } Clock c= (Clock)x; return hours == c.hours && mins==c.mins && secs= c.secs; } ------overloads it-----

Write a class that has an instance variable which is an array of Cat objects, called kitties. Write a method that returns a reference copy of kitties. Write a method that returns a shallow copy of kitties. Write a method that returns a deep copy of kitties.

public class Circus { private Cat[] kitties; public Cat[] referenceCopy( ) { return kitties; } public Cat[] shallowCopy() { Cat[] copy = new Cat[kitties.length]; for (int i = 0; i < copy.length; i++) { copy[i] = kitties[i]; } return copy; } public Cat[] deepCopy() { Cat[] copy = new Cat[kitties.length]; for (int i = 0; i < copy.length; i++) { copy[i] = new Cat(kitties[i]); } return copy; } }

Write a java class called "Fred". Put in a main method. Have the main method store your age in a variable named age. Then main should print out a line that has your name, followed by your age. (Use a ?string literal? for your name, but use the variable to access your age.)

public class Fred{ public static void main(String args[]){ int age = 12; System.out.println("Eileen W, age is " + age); } }

If someone showed you a Java class, how can you quickly identify which members were part of the API for that class?

public members

Write a method called smallSum that takes two int parameters, x and y. If the absolute value of the sum of the integers is more than 100, throw an ArithmeticException, passing the String "I don't like bi\ g numbers" to the constructor of the exception. If the sum is less than 100, then return the sum. Write a quick driver to test out your method. After making sure everything works correctly, modify the driver so \ that it catches the exception and prints out the message that was passed to the exception's constructor, but doesn't crash the program.

public static int smallSum(int x, int y) { if (Math.abs(x + y) > 100) { throw new ArithmeticException("I don't like big numbers!"); } return x + y; } public void static main(String[] args) { try { smallSum(50, 60); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } }

Name and describe the two visibility specifiers that you should know at this point.

public: these members are visible everywhere private: these members are visible only within the class

Consider the Basket class, partially shown below. What kind of copy of the array is being returned by the getter? public class Basket { private Egg[] eggs; ... public getEggs() { return eggs; } ... }

reference copy

"e"

reference to the Exception Object

rewrite this using the ternary operator: if (size < 100){ return "large"; }else{ return "small"; }

return (size < 100) ? "large" : "small"

get(int index)

returns the element at the given index

Why is the substring method expensive

runtime is O(n^2) because you have to copy characters over

Suppose you have a String variable called s. What expression will return the number of characters in the String?

s.length();

ternary operator X? Y : Z What must Y and Z be

same type

Which of the following two code fragments is a better choice? if (x == 4) { System.out.println("A"); } if (x == 6) { System.out.println("B"); }_________________________________________________ if (x == 4) { System.out.println("A"); } else if (x == 6) { System.out.println("B"); }

second one

Define the term "byte"

sequence of 8 bits

Which of the following is the best definition for the term "byte"?

sequence of 8 bits

Assume that x is an array of String references. Which kind of copy of the array is made is below? String[] y = new String[x.length]; for (int i = 0; i < y.length; i++) { y[i] = x[i]; }

shallow copy

Consider the Basket class, partially shown below. What kind of copy of the array is being returned by the getter? public class Basket { private Egg[] eggs; ... public getEggs( ) { Egg[] copy = new Egg[eggs.length]; for (int i = 0; i < eggs.length; i++) { copy[i] = eggs[i]; } return copy; } ... }

shallow copy

GETTERS FOR ARRAYS ARE DIFFERENT AND CANNOT BE NORMAL GETTERS. YOU HAVE TO USE EITHER A

shallow or deep copy

The "catch" block is only executed if

something weird (which solicits the exception to be thrown) happens. If the program runs exactly as expected, the catch block is ignored

Javadoc comments

starts with a forward slash and two asterisks (/**) and end with an asterisk forward-slash (*/) Are used to generate documentation with Javadoc

.equals

state of objects

What kind(s) of variables are given default values if they are not initialized explicitly?

static instance

What advantage do you gain from using one of the types of integer types that requires MORE memory?

store larger values or wider range of values

Which of the following represent possible identifiers (names of variables, methods, classes, etc.) in Java? We're not asking whether or not they are good style, just whether or not they satisfy the language requirements. (Select all that apply.) string 3OfAKind #goals int $balance_in_account

string, $balance_in_account

Gausses Formula

sum of numbers 1-n = n*(n-1)/2

Rewrite using switch statements. if(x == 3) { A } else if (x == 40){ B }else if(x == -5){ C }else{ D }

switch(x){ case 3: A break; case 40: B; break; case -5: C; break; default: D; }

Suppose you accidentally type "System.out.pint()" instead of "System.out.print()". What kind of error is this? syntax error logical error semantic error

syntax

Why are linked lists favored

take less time when inserting elements

Unit Testing

testing of individual programs by itself to make sure it satisfies contract

integrated testing

testing several components together working up to entire project

If an exception within a method isn't handled via an Exception Handler,

that method is popped off the Call Stack

There's two different parts of an exception:

the Exception and the Exception Handler

If the handler isn't within the Method where the Exception is created,

the Method in which the Exception is created is popped off the Call Stack

Aliasing is a ONLY a problem for mutable objects because

the Object can be changed, but it must be changed EVERYWHERE and this impacts the rest of the code

If all objects of a specific class are mutable/immutable,

the class is mutable/immutable

If there is no handler for a certain exception what happens with the finally block?

the finally block is STILL executed

the more data we process

the longer it takes

The String[] args parameter in the main method header allows

the program to receive arguments from the operating system command-line.

inheritance (in Java)

the relationship where a more specialized subclass is also of the type of a more general superclass

block scope

the scope of a variable declared within a statement block; a variable with block scope can be used only within the statement block in which it is declared, and only after its declaration statement

The exception might print early because

there are multiple threads of the program running at the same time

if the thing that the arrows are pointing at is mutable

this is a problem -arrays are always mutable, thats why reference copys are bad

public class Rabbit { public Rabbit(double size) { ...} public Rabbit() { // What goes here? } } Which of the following statements could be inserted into the second constructor so that it calls the first constructor with the argument 9.2?

this(9.2);

Assume the following class declaration, partially shown: public class Classroom { private String roomNumber; // e.g.: "IRB0324" private int capacity; // number of seats in the room public Classroom(String roomNumberIn, int capacityIn) { roomNumber = roomNumberIn; capacity = capacityIn; } public Classroom(String roomNumberIn) {// What should go here? } ... } What should you type into the body of the second constructor, so that it initializes the current object with the room number that is provided as an argument, and with a capacity that is always set to 100? Your answer must be a single statement that invokes the first constructor.

this(roomNumberIn,100);

Strings being immutable is bad because

time and memory (because this creates a lot of garbage in the Heap)

When you pop an entry into the stack does it go on the top or bottom?

top

When you push an entry into the stack does it go on the top or bottom?

top

Usually, the author of a Class states whether their Class is mutable/immutable at the

top of the API

(True/False) A method that is given a default implementation in an interface can be called on an instance of a class that implements the interface, even if the method does not appear in the class.

true

(True/False) In Java, arrays are objects.

true

(True/False) These two expressions carry the same value: (Assume that in both expressions, x starts with the same value). x-- x++

true

If you change a class in such a way that the API changes, then other classes which depend on this one will have to be re-coded.

true

True/False: In java, when you pass a reference variable as an argument to a method, it is possible for the method to modify the object to which the variable refers.

true

What values can a boolean variable achieve?

true or false

FINALLY BLOCK-in the try/catch block and there's a return which terminates the method

try block > catch block > finally block

FINALLY BLOCK- one exception is thrown and the handler is found locally

try block > catch block > finally block > remaining code outside

FINALLY BLOCK- No exceptions are thrown

try block > finally block > remaining code outside

Exception Handler

try { <code which might throw an exception> } catch (ExceptionClass e){ <put handler here> }

Catching multiple exceptions

try { <put troublesome code here> } catch (NullPointerException e) { <handler here> } catch (Arithmetic Exception e){ <other handler here> } catch (IOException e){ <other handler here> }

Finally block

try { <put troublesome code here> } catch (NullPointerException e) { <handler here> } catch (Arithmetic Exception e){ <other handler here> } catch (IOException e){ <other handler here> } finally { <code that is ALWAYS executed> } -follows all catch blocks, and executes after the program exits the corresponding try or catch blocks !!!!!ALWAYS RUNS!!!!! USE TO CLEAN UP CODE

Implicit Casting

type widening

Declaring a 2d ragged array the long way

type[ ] [ ] name = {value, value, value}, {value, value}....

operator precedence hierarchy

unary, multiplicative, additive, compairison, equality, and, or, assignment

If you don't plan to manipulate the string a lot,

use String

If you plan to manipulate the string (in a loop),

use StringBuffer

++x

value is x after incremented

Local variables

variables that are declared inside a method, stored on call stack

public

visible in the entire project

push

when something is added to the top of the stack- always goes on top

Assume that x and y are variables of type char. How to check whether or not x and y are the same character?

x == y

double x= 58.7; int y= (int) x;

x does not change, just a copy is put into y

After the following code has executed, what are the values of x and y? int x = 7; int y = --x - 2;

x is 6, y is 4

Assume that x and y are variables of type String. Which of the following boolean expressions should be used to check whether or not x and y contain the same sequence of characters?

x.equals(y)

Never forget that you should not compare two Strings with the == operator. Suppose you have two String variables, x and y. Give an expression that can be used to check whether or not the Strings x and y are identical.

x.equals(y);

After the following code has executed, what are the values of x and y? int x = 4; int y = 6 + x++;

x=5, y=10

How to instantiate the cats

x[0] = new Cat("Fluffy"); x[1] = new Cat("Princess"); x[2] = new Cat("Spot"); x[3] = new Cat("Steve");

Using the ternary operator (?:), write a single statement that is equivalent to the following code fragment, and only includes one assignment operator. DO NOT INCLUDE ANY SPACES IN YOUR ANSWER. if (x < 5) { y = 20; } else { y = 50; }

y=x<5?20:50;

Can you have multiple catch blocks for one try block?

yes

Is the following statement valid: boolean q = 17 < 25;

yes

Is the following statement valid: double y = 12;

yes

can you use this in instance methods

yes

public static void h(int x) { x = 4; bar(x); } After the call to the bar method is over, will the variable x still be set to 4?

yes

Immutable classes are preferred because

you can alias with no issues

Whats better about using interfaces?

you can only extend one class, but you can implement as many as you want

public default instance methods

you can put code in and the class that implements the interface inherit the coed and are able to override the method w/ own implementation

why do Java Collections Framework rely on equals method being correctly

you do not check if the exact object is in the collection, just one that looks the same

How many Cat objects are intialized? Cat[] x; x = new Cat[4];

you don't have 4 cats until you've initialized the 4 cats

When comparing performance of two algorithms from different categories, what can we say about performance?

you have to say for sufficiently large values of n, one category is better than another but that is all you can say ex : 16 steps - all of the big o are abbreviations "some linear function" "some quadratic function" so you cannot tell specifically

Accessing a class from a different package

you have to use import: import wholePackageName.innerPackageName...nameOfClass or use the fully qualified name every time you use the class

StringBuffer being mutable is bad because

you need to do copying instead of aliasing

JUnit cons

you never know if your code is precisely correct

If an Exception has been thrown without a Handler

you will get a Red Error Message on the console

When you throw an exception

your program will no longer be executed. This is because Java is looking for an Exception Handler (which fixes the problem)

Java Generics

• technique that allows us to define methods and classes that work with a variety of data types without the need for explicit casting.

static variables

• variable is connected to the whole class, not individual objects • all variables of the class share this one variable • with the keyword final it is used to create a constant

How many bytes are in a gigabyte?

1 billion or 2^30 bytes

What is the value of the following expression (in Java): 6 + 5 / 2 * 2

10

How many different values can be represented by 4 bits?

16

roundoff error

A numerical error that occurs because floating-point numbers are stored as approximations rather than as exact values.

super class

Class that contains the code with both state and behavior that can be extended by its subclasses.

Can this be used in an interface? public int x;

False- no instance variables

public static void foo( ){ Dog x= new Dog( );

ONLY ONE DOG

FlyingObject x; What can you do with x?

Only the methods listed in the interface x.takeOff( ): x.fly( ); x.land( );

Primary Memory Device

RAM


Conjuntos de estudio relacionados

DLC 114: Conducting Squad Drills and Ceremonies

View Set

Chapter 1 Introduction to Human Relationships

View Set

PSY-425-CHAPTER 9- Conceptual Knowledge

View Set

study guide 4-6 window server 2019

View Set

Ch 2.3 - How successful were attempts to improve international relations from 1924-29?

View Set

Pharmacology medical surgical drugs (final hesi) evolve

View Set

Chapter_4_Network Protocols and Services

View Set

Chapter 37: Epidemiology and Public Health Microbiology, Ch. 37 Epidemiology and Public Health Microbiology

View Set