Java Exam

ndifranco94's version from 2015-12-10 08:09


Question Answer
What is the type of a valuewhat a piece of data represents, specified by PROGRAMMER/PROGRAMMING LANGUAGE
Primitive typespredefined by the language
Compound (reference) typesboth predefined by the language and programmer created
What are the primitive typesint, double, char, boolean, long, short, byte, float
What does the Java compiler do with types?verifies you use each type properly
How does Java use types?determines what values can be stored in a variable and what operations can be performed on it
Strictly typedevery piece of data in Java has a well-defined type
A compound type can containvariables of any type (fields), methods, other compound types
Fieldvariable of any type
Methodfunction or procedure that takes 0 or more inputs, does something, and produces an output (or not)
What can we do w/ a compound type?access a field, call a method, access the inner type, create an instance of the type
Instancesif Movie is a type, and instance would be Star Wars, Boyhood, etc
3 Pre-Defined Compound TypesJFrame, Math, Object
Creating an instancenew type(input to constructor)
What happens when you create an instance?allocate space in memory, initialize the instance using constructor input, new returns the location in memory for the instance
Objects storethe address of the location in memory for the object
Two types of fieldsInstance (non-static) and Class (static)
Instance field (non-static)each instance has its own, Ex. rootPaneCheckingEnabled
Class field (static)every instance shares the same variable, Ex. Math.PI
Typecastcan convert b/n values of ANY primitive type EXCEPT boolean
Narrower to wider conversionAutomatic
Wide to narrower conversionrequires explicit typecast
Primitive types from Widest to NarrowestWIDEST double, int, char NARROWEST
Arithmetic operators+ - * / %; narrower operand automatically widened to wider one (both are widened to at least int), result = wider type
Comparison operators< <= > >=; narrower operand automatically widened to wider one, result = boolean
Equality operators== !=; operands must be related types, narrower operand automatically widened to wider one, result = boolean
Boolean operators&& || ! & |; operands = boolean, result = boolean
&& and ||short circuit operators, won't evalute second part if not necessary
Assignment operator=; type is type of variable, converted if narrower
Can you typecase b/n primitives and objects?NO
Why do we typecast?to allow certain operations to be performed on variables
How is data represented on a computer?series of switches
int is stored as32-bits
double is stored as64-bits
char is stored as16-bits
Why do programmers need to know how int, double, and char are stored?b/c there are different limits on each
How is computer arithmetic different?base 2, operates on 2's complement which allows for the representation of many numbers using a series of switches, LIMITED SIZE OF NUMBERS THAT DOESN'T OCCUR IN REAL ARITHMETIC
= and === is an assignment operator, returns type of variable, == is an equality operator, returns boolean
What must be done with a variable before it is usedit must be DECLARED; Ex. int a, String s, double d
The first time you use a variableyou must GIVE IT A VALUE
privatecan only be accessed within the declared class itself
publiccan be accessed from any other class, inherited by all child classes
instance variablesaccessible by any method in a class
parameter variablesonly available to the method that receives the parameter as input, only exists IN THE METHOD BODY
local variablesonly exist within a method, unless they are returned, are deleted at THE END OF A COMPOUND STATEMENT
How do you define a classClass Header and Class Body
Class headeraccess modifier, class, name of class, extends, parent class......Ex. public class MyFrame extends JFrame {
How do you create a fieldaccess modifier, field type, field name.....Ex. private String firstName = "Nick"
How do you create a methodMethod header, Method body
Method headeraccess modifier, return type, method name, input parameters....Ex. public void setFirstName(String firstName) {
Method bodylocal variables and code, possibly a return statement
staticused by the entire class, exists as long as the program is running, does not act on a object or contain this....Ex. employee.getSalary()
non-staticused by a specific instance, exists as long as the instance exists, acts on an object and contains this....Ex. employee1.getSalary()
Constructorsinstance method with no return type and the same name as the class....Ex. public Account(String firstName) { this.firstName = firstName; }
How does a constructor work?the first line of a constructor is a CALL TO THE PARENT CLASS CONSTRUCTOR, initializes instance fields, executes rest of body
What does new do?ALLOCATES SPACE in memory for the instance, initializes the instance by CALLING THE CONSTRUCTOR method using the input to new, RETRIEVES THE ADDRESS of the instance
return valueafter method is executed, returns predefined type; can be primitive or reference type
Method Overloadingmultiple methods with same name but DIFFERENT PARAMETER SIGNATURES (# of parameters, type of parameters, order of parameters)
Method Overridingclass can change behavior of an inherited method by writing a replacement method w/ exactly the SAME NAME, PARAMETER SIGNATURE, AND SAME (OR NARROWER) RETURN TYPE
@Overridetells compiler you want to override a method
Polymorphismall non-primitive types are many types at the same time
True typetype the object was created as. never changes, determines WHICH METHOD VERSION IS EXECUTED
Current typewhich of the polymorphic types the object is currently being used as. changes constantly (typecasts, return type, variable type), determines WHAT FIELDS ARE ACCESSED AND WHAT METHODS YOU'RE ALLOWED TO CALL
thisa reference to the current object on which a method or constructor is being called
super a reference to the parent object on which a method or constructor is being called
super()calls the parent class constructor
this()used to call current class constructor. can be used to explicitly call constructor when there are no inputs....Ex. public Account() { this("Nick"); }
Why make field private?so you don't use them in methods, which would prevent polymorphism from working
What is public and what is private?Fields = private, Methods = public
Why make methods public and fields private?makes it easy to write classes that extend your class
Heapunorganized, stores all CLASSES/INSTANCES, objects are maintained as long as there is a reference to the object
Stackorganized, used for method calls, stores all LOCAL VARIABLES + PARAMETERS OF THE METHOD, BOOKKEEPING INFO (where to look in memory)
Mini-Framecreated to store variables declared in compound statements
Each time a method is called, what happens in memory?a STACK FRAME is placed on top of the stack
Each time a method exits, what happens in memory?the STACK FRAME is REMOVED
+ operator (Strings)concatenates the operands by creating a NEW STRING
Two ways to create a string"input" or new String(input)
StringBuilderallows you to build a new string using loops, has append() method for this
charAt()returns the character at the index that is input (starts at 0)
Packagea bundle of related classes that can be imported all at once, makes it easier when performing certain tasks...Ex. = reading and writing classes
Java APIApplication Programming Interface, the set of classes included with the Java Development Environment, allows you to see the classes available in Java and methods available within each of those, makes it easier to see what functionality is already built in to Java classes
While loopwhile(condition) {
For loopfor(initial statement; condition; increment statements) {
For-Each Loopfor(elementlist), works on iterators and arrays
How to test loopsTest 0, 1, many (like 0, 1, many mismatches in palindrome)...Test first, middle, last (like first character mismatch in palindrome)...Test null
How to test if statementstest if condition, test each else or else if condition, test null
Purpose of the loop iteration subgoal (loop invariant)a condition that holds true for evey iteration of a loop, helps us determine exactly what must happen in the loop body, must be true before the first iteration + if true at the beginning of the loop body, true at the end too
Weakest precondtionminimum condition that needs to be true before we start a loop iteration if we want the subgoal to be true at the end of the iteration
is-a ruleIf A is-a B then we make A and B classes where A extends B. Ex. Square is-a Rectangle
has-a ruleIf A has-a B, then make B a method/methods in A. Ex. Square has-a area
Difference b/n interface and abstract class?Abstract class contains everything a normal class would + method stubs, interface can only contain method stubs
Interfacelike a class, but it can only contain method stubs (the method header, but no method body).
Abstract classclass that CANNOT be directly instantiated with new, contains everything a class contains (constructors, fields, methods) + method stubs (abstract methods)
JavaDoca tool that is used to generate documentation from Java source code that has documentation in a predefined format (using @ tags)
charAt(int index)allows you to get the character at a specific index
\nend of line character
When to use + and when to use StringBuilder?StringBuilder is used for appending, + is used to combine two finalized strings
Why does Java have wrapper classes?to allow primitive values to do things only objects can do (like be added to an ArrayList), provide functions like CONVERTING PRIMITIVE TO STRING and back or COMPARING OBJECTS
Unwrappingconverting from wrapper to primitive, uses a method Ex. y is an Integer, y.intValue() = int
Wrappingdefine a primitive as a wrapper class Ex. Integer x = 0 instead of int x = 0
Integer.parseInt(String s)converts string to integer
Arraya collection of variables of the same type, stored in a contiguous chunk of memory.
How to access elements in an array?array[index]
How to initialize an array?int[] array = new int[20], initializes an array of ints with 20 blank spaces
How to declare array variable?array[3] = 5, now the 4th value of array is 5
How to copy an array?need to make a FOR LOOP
How to initialize an array with values?int[] array = {1,2,3,4,5}
How to insert into an array?for loop that starts at end and increments every value forward until it hits where k goes
Multi-dimensional arrayjust an array of arrays, int[][] array = int[5][10] has 5 "rows" and 10 "columns"
Initialize multi-dimensional array shortcutint[][] array = {{1,2,3}, {4,5}, {6,7,8,9}}
Linear searchgoes through each value without jumping, time grows at same rate as length of list O(n)
Binary searchstarts in middle of sorted list, checks if value is larger or smaller than value you are looking for, sets new max or min and splits that in half, time grows at slower rate than list O(log n)
Binary search only works forSORTED LIST
InsertionSortfinds largest value and puts it at the top, repeats until finished, on average takes n^2/4 steps
MergeSortsplits list, merge sorts each list, merges the two lists into one list, on average takes 2n*log(n) steps
Difference b/n linear and binary search?Binary grows at O(log n), linear grows at O(n)
Diffrence b/n insertion sort and merge sort?merge sort grows at 2n*log(n), insertion sort grows at n^2/4
Linked Listdata structure that stores values of the same type, can easily change size but only gives fast access to a few elements at a time
How to create a Linked List?LLNode<Double> list -= new LLNode<Double>(1.0, null);
How to add to a Linked List?list.setNext(new LLNode<Double>(2.0, null);
How to add 0 to beginning of Linked List?list = new LLNode<Double>(0,list)
How to insert into Linked List?create node, set next for new node right node, set next to left node to new node. Ex. list.getNext().setNext(new LLNode<Double>(1.5, list.getNext().getNext());
Generic typeT, allows for many different type inputs
How to create a class with a generic?public class WindowList<T extends JFrame> extends LinkedList<T> {
How to instantiate object with generic type?WindowList<FunFrame> list = new WindowList<FunFrame>(), JUST FILL T WITH THE TYPE YOU WANT
?wildcard, lets type be anything, Ex. ? extends JFrame --> would allows anything under JFrame
Arrays vs. Linked Lists?Array is good when you need FAST ACCESS to random values, Linked List is good for when SIZE IS CHANGING and values are being ADDED/DELETED
Linked Lists vs Array Lists?Linked List is good for when SIZE IS CHANGING and values are being ADDED/DELETED, Array List is good when you need FAST ACCESS to random values (Array List is just an array that resizes itself)
Exceptionerrors in a program
How to create an exceptionimproper type, out of bounds, etc
Throw an exceptionthrow new ExceptionType() or throw e if e is already an exception
Unchecked exceptionjust stops method
Checked exceptionprogrammer must specify what to do if the exception is thrown
finallycomes after try and catch, its the code that's always executed after exiting try/catch
finalthe variable always contains the same value or the variable will always reference the same object address
What is the purpose of the main method?To allow Java programs to run as STANDALONE PROGRAMS
How does main work?Contains statements that are evaluated until end of main is reached and program terminates
Inner Classclass inside another class, Ex. public static class FunClass {
Static Inner ClassesFunFrame.FunClass f = new FunFrame.FunClass()
Nonstatic Inner Classeshave to make a fun frame then FunFrame.FunClass f = FunClass()
Anonymous classdefined in the new expression that is creating an instance of the class, Ex. button.addActionListener(new ActionListener { code } )
Unit Testingverify logic of pieces of program are right
Testing rulesfirst, middle, last .... zero, one, many
Reflectionmakes it possible to inspect classes, interfaces, fields, methods at runtime. Ex. getClass
Threadan execution on your computer
Problem with multiple threads?they can interleave
How to fix multiple threads from interleaving?lock code with synchronized
synchronizedsays that threads cannot access piece of code if another thread is already
lambdashortcut for creating anonymous classes
When do you not need a type in <>?When Java can figure out what type is needed

Recent badges