CNIT 255 Final
How can you make sure you're overriding a method rather than just accidentally introducing a new method?
@Override
What are the two floating point types and their size?
Float(4 bytes) Double(8 bytes)
GUI stands for . . .
Graphical User Interface
What is an assertion?
Used to provide a check for something like if x cannot be negative you can do: assert x >=0 also used to check parameters and assumptions
Shortcut to make a new line
\n backslash n
Shortcut to make a tab
\t backslash t
What is the benefit of using assert instead of illegal argument exception?
asserts can be easily enabled or disabled, which improves performace
You use == to compare strings a. true b. false
b. false you use "Hello".equals(greeting)
What are runtime errors?
errors that are the programmers fault: null pointers, out of bounds, ...
What do you do with a class? (inheritance)
extends
You can instantiate an interface a. true b. false
false
True or false: if you try to cast to an invalid type the result is null. ❏ true ❏ false
false it will be a compile error
True or false - the interface keyword defines a special kind of class. ❏ true ❏ false
false- interface is NOT a class
What keyword do you put in front of int and double to make them constants?
final
To produce a game like tic tac toe what layout would you use?
gridlayout
How to turn off an assertion?
java -disableassertions MyApp java -da:MyApp
How to turn on an assertion?
java -enableassertions MyApp or java -ea:MyApp
How to execute a program?
java MyFirstProgram
How to compile myfirstprogram? and what will it produce
javac MyFirstProgram.java MyFirstProgram.class
Can inner classes access the data members and methods of the outer class?
yes
Can you throw multiple exceptions?
yes
How can you make a "true copy" of an array?
(Arrays.copyOf())
What is the difference between an unchecked exception and a checked exception in Java?
- Unchecked exceptions are RuntimeExceptions and its subclasses - Checked exceptions are all other exceptions - Checked exceptions must either be caught (i.e., try-catch) or declared in the method signature (i.e., throws)
What are the two ways to put comments in java?
/* */ or //
What length does an empty string "" have? what does null indicate?
0 No string at all
What is the value of a field that is not explicitly set in a constructor?
0, null, false
What would be the output of the following program? public static void main(String[] args) { int[] primes = {11, 13, 17, 19, 23, 29}; System.out.println(primes[1]); System.out.println(primes[5]); }
13 29
How many integers are created? int multi[][] = new int[4][4];
16
What is printed? int x = 1; while(x < 5) { x = 2*x + 1; } System.out.println(x);
7
Read the following example. A) How does it use encapsulation? B) How does it use inheritance? C) How does it make polymorphism possible? abstract class Animal{ public abstract void makeSound(); } class Dog extends Animal{ private static final String sound = "bark"; @Override public void makeSound() { bark(); } public void bark(){ System.out.println(sound); } } class Cat extends Animal{ private static final String sound = "meow"; @Override public void makeSound() { meow(); } public void meow(){ System.out.println(sound); } }
A) Encapsulation: Dog and Cat both have their sound as private. B) Inheritance: Dog and Cat extend the Animal abstract class. C) Polymorphism: If you create a variable of type Animal, you can assign the variable to an object of type Dog or Cat. You can then call makeSound on this variable, regardless of whether it was assigned to a Cat or a Dog object. This is known as run-time polymorphism.
What best describes the "String [] args" in a main() method? A) It allows someone to pass arguments into your program when they run your code. B) It explains to the compiler that your program is to be run from the command line instead of double clicked from the desktop. C) It defines a variable called String of type args. D) It's not typed right and will cause a compile-time error.
A) It allows someone to pass arguments into your program when they run your code.
if "class X extends Y", which is most true? A) X is a Y B) X has a Y C) Y is an X D) Y has an X
A) X is a Y
3) How do you find the length of an array "arr"? A) arr.length B) arr.length() C) arr.size D) arr[-1] E) System.array.length(arr);
A) arr.length
Which conversions are "automatic"? List all that apply: A) int => double B) double => int C) char => int D) long => int E) double => short
A) int => double C) char => int
2) What is an abstract function? When should we use it? Can it be instantiated?
An abstract function is a function that has no implementation. We use it when we want our subclasses to provide the implementation for it. No
What can you call Arrays.sort() on?
Any array of objects, where the objects in question implement the Comparable interface compareTo
What are the differences betweenn Array and ArrayList
Array has a fixed size, ArrayList has a dynamic size Array can contain both primitives and objects. ArrayList can only contain objects Array members are accessed using []. ArrayList has methods.
When assertions are enabled what type of error is thrown?
AssertionError
What best describes a String? A) It is a primitive variable type in Java B) One can be created by putting it in single quotes, 'like this' C) Strings are sequences of unicode characters. D) You can only call a method on a String if you put it in a variable first.
C) Strings are sequences of unicode characters.
How do you get the number of elements in an ArrayList called list? A) list.size B) list.length C) list.size() D) list.length()
C) list.size()
What will the value of x be after the following expression is evaluated? int x = 14 % 10 + 5 / 4; A) 5.25 B) 2.65 C) 5 D) 2
C. 5 because it is an int
What are some strategies for dealing with when an error occurs? A) Return an error code. B) Terminate the program. C) Throw an exception. D) All of the Above
D) All of the Above
Why might you ever use a do/while loop instead of a regular while loop? A) You wouldn't - do/while isn't a valid Java construct. B) It lets you define variables used in the loop conditional that go away when the loop is done. C) It saves the value of the loop expression and checks that only after running the loop. D) It guarantees that the loop will run at least once.
D) It guarantees that the loop will run at least once.
What is returned by Math.pow(3,2) A) "bang!bang!bang! bang!bang!bang!" B) 8 C) 9 D) 8.0 E) 9.0
E. 9.0 when Math. something is used it is a double
In your own words, what is a "GUI Event"?
It is a message generated when "something interesting" happens, such as a button being clicked or a window closed; and also the act of a response being triggered for that "something", in the form of a method being called with that message.
In order to create a component, you must extend the J. . . class
JComponent
The methods setDefaultCloseOperation and setVisible are called on an object of type J. . .
JFrame
How to use a logger?
Logger.getGlobal().info("whatever");
How do you turn off logger?
Logger.getGlobal().setLevel(Level.OFF);
How to do a to the power of b
Math.pow(a,b);
How to do square root of x?
Math.sqrt(x)
Which of these should be a class, and which of these should be interfaces? a. Pig b. Bird c. Fish d. Walking e. Flying f. Swimming
Pig, Bird, Fish - Classes since they have a unique structure. Walking, Flying, Swimming - Interfaces since they are things that various animals can-do.
Why is finally used?
To clean up code. Closing files, connections, streams,...
What are assertions intended for?
To terminate a program, not for recovery
What does it mean that a string is immutable?
We cannot change a String object. We can change where a String variable points to, but not the object itself. Example: String s1 = "Original"; String s2 = s1; // s1 and s2 now point at the same string - "Original" s1 = "Novel!"; System.out.println(s2); // still prints "Original" When we re-assigned s1 to "Novel!", we only changed the reference. Not the object that s1 pointed to.
When do you use a try/catch block?
When an exception is thrown and there is no one to catch it, use a try catch you can catch multiple exceptions with multiple catch clauses
When might you prefer an ArrayList over an Array?
When you don't know how many elements you're going to need ahead of time. Or you want to make use of add() and remove()
What is a local inner class?
a class defined inside of a method
What is an inner class?
a class inside another class that is defined
What does a compareTo method return?
a positive integer if otherObject comes before this object zero if two are indistinguishable a negative integer otherwise
What is displayed when an exception terminates a program?
a stack trace
What is polymorphism?
a variable can refer to multiple types
What's the difference between inheritance and implementing an interface?
a) A class can only extend (inherit from) 1 class. You can implement multiple interfaces. b) Inheritance generally describes an is-a relationship(nouns). In inheritance you define the base structure for subclasses. c) Interfaces generally describe a can-do relationship. (verbs ing)
Every manager is an employee, but not every employee is a manager so: A) manager is a ____class of employee. B) employee is a ____class of manager. C) a.compute is an example of ____ binding.
a. subclass b. superclass c. dynamic binding
In the Model-View-Controller pattern: a. The . . . displays the data. b. The . . . handles events. c. The . . . is pure data with no visual appearance.
a. view b. controller c. model
What does logging API do?
better than using system.out.println can direct the information to different places
What are the four integer types and their sizes?
byte(1 byte) short(2 bytes) Int(4 bytes) Long(8 bytes)
Which of the following statements is correct? a. A final class cannot be public. b. A public class cannot be final. c. A final class cannot be extended d. final is not a valid class modifier.
c. A final class cannot be extended
what's the difference between break and continue?
continue skips the rest of the current iteration of a loop; break skips the rest of the loop altogether
Are local classes: a. private b. protected c. public d. never any of them
d. never any of them
To make sure the last bit of a statement runs in a try/catch block without terminating what do you add?
finally after all the catches
Give two examples of layouts in Swing.
gridlayout flowlayout
Would an if/else chain or a switch statement be better for each of these programs? Why? Changing power level based on temperature data from a thermometer every 5 minutes. a. Below -10°C --> 100%. b. Between -10°C and 10°C --> 80%. c. Between 10°C and 25°C --> 60%. d. Greater than 25°C --> 40%.
if/else because you can't use conditions with switch. But they are easy to use with if/else
What do you do with an interface?
implements
How would you import every class in the java.util package without tediously importing each one, one at a time?
import java.util.*;
What is the import statement you add before everything?
import java.util.*;
What does s.trim().toLowerCase(); do?
it removes the spaces in front of and after the word and makes all of it lower case
what is n+=4
n=n+4
As opposed to declaring an array, what keyword actually creates an array?
new new int[] {17,4,9}
Assume we have two Integer objects, num1 and num2. a) How can we test if num1 is equal to num2? b) How can we test if num1 is smaller than num2? (Hint: Look at the Integer class in the Java API)
num1.equals(num2) num1.compareTo(num2) < 0;
What are related classes grouped into, in Java?
packages
True or false - classes are allowed to have classes defined within them. ❏ true ❏ false
true
True or false: two classes are allowed to have the exact same name as long as they are in different packages. ❏ true ❏ false
true
True or false: you are allowed to change the state of a final variable (e.g., the "name" or "salary" instance field of an Employee variable). ❏ true ❏ false
true - you just can't reassign the variable to a different object
How do you extend a class to make a subclass?
use the keyword extends
If you can't handle an exception you have caught in a catch clause, what should you do with it?
use the throw keyword to throw it again
Why are inner classes useful?
useful for hiding implementation details
Mark all that are true: ❏ In Java, "Global Data" is allowed to exist outside of a class. ❏ Any variable that isn't a "primitive value" is an object. ❏ An "instance" of a class C is an object of type C. ❏ OOP stands for "Object-Oriented Procedures."
❏ Any variable that isn't a "primitive value" is an object. ❏ An "instance" of a class C is an object of type C.
Mark all that are true of interfaces: ❏ A class may only implement at most one interface. ❏ If a class implements an interface, it must implement all of the methods declared in the interface or be declared abstract. ❏ An interface is declared to be implemented by a class using the extends keyword. ❏ Just like with super class types, via Polymorphism, you can use an interface type to declare a variable that refers to any object that implements the interface (e.g. Comparable c;).
❏ If a class implements an interface, it must implement all of the methods declared in the interface or be declared abstract. ❏ Just like with super class types, via Polymorphism, you can use an interface type to declare a variable that refers to any object that implements the interface (e.g. Comparable c;).
Which fields can a subclass access from a superclass? ❏ public ❏ private ❏ protected
❏ public ❏ protected
Rewrite this to declare that func() can throw a GnarlyException public void func() {
public void func() throws GnarlyException
Someone has called your method with an invalid argument. The right thing to throw is an IllegalArgumentException. What line of code would do so?
throw new IllegalArgumentException("Wrong input to method!");
A JPanel is an invisible container that can hold components. True or False?
true
True or false - classes are allowed to be defined inside a method. ❏ true ❏ false
true
What does scanner class do?
reads input from a console(or from a string)
What happens when the computer goes to run this line of code? System.out.println("String".substring(2, 6));
ring
The ____ keyword is used to invoke a superclass constructor.
super
Would an if/else chain or a switch statement be better for each of these programs? Why? Performing a specific action based on character input from the keyboard. 'q' - quit. 'c' - continue. 'y' - yes. 'n' - no. 'h' - help.
switch is often preferable when you need to choose between multiple predefined values, based on 1 variable
What is a checked exception?
the facts of life exceptions like flaky internet that the compiler checks that you deal with subclasses of exception, but not of runtimeexception
Compare and contrast the this and super keywords:
this is a magic variable referring to the current object within an instance method, and can be used to disambiguate variables with the same name. super is a reference to the super class