Uploaded by dinky0717

Intro to Computer Science - Complete Final Exam Review

advertisement
Arrays:

Correct format/syntax for declaring arrays
A:
String [] array = new String [length]
Also
String array [] = new String [length]
Also
String [][] array = new String [length row] [length column]

Java library for arrays

A:
.asList - returns a fixed-size list backed by the specified array
.binarySearch- searches the specified array for the specified value using the binary search algorithm
.equals - returns true if two specified arrays are equal to one another
.fill - assigns a specified value to each element of the specified range of the specified array
.sort - sorts the specified array into ascending numerical order
ArrayLists

Stores an unlimited number of objects. Let's us redefine arrays without having to change their
lengths etc. literally a godsend

Java.util.collections lets youu do all the stuff to arrays that java.util.arrays does. Have to import
java.util.arraylists to use arraylists tho
Methods:
+add(), --adds an element to the list
+clear() -empties a list
+contains() - checks if the list contains an element
+get() - gets an element at a certain index
+indexOf() - returns the index of the first matching element in the list
+isEmpty() - returns true if the list is empty
+lastIndexOf() - returns the index of the last matching element in this list
+remove() - removes the first matching element in the list. Returns true if the element is removed
+size() - returns the number of elements in the list
+remove - removes the element at the specified index
+set - sets the element at the specified index

Syntax:
ArrayList <primtype(wrapped name)> name = new ArrayList<primtype>();
Ex:
ArrayList <Integer> hello = new ArrayList<Integer>();
NOT
ArrayList<int> hello = new ArrayList<int>();
Sorting:

How to do a Selection Sort:
A: Selection sort is when you take the smallest element of an unsorted array and bring it to the front.
You go from each item (left to right) until the smallest one is found. Then you bring that to the front (as it
is sorted) and then sort the remainder in a similar fashion.
To Do:
1. You have an array, a new array, and two for loops. One going through the array letter by letter
(i=0) and one looping through the remaining array positions for comparison (i= 1). You also have
a temp variable declared outside of the loops.
2. Within the second for loop is an if/ese statement along with the temp variable set to the
PLACEMENT NUMBER of the current smallest value. This if else statement will run comparing the
value in the first for loop to the values in the second for loop. If a value is less than the current
temp, then temp's value changes to the PLACEMENT NUMBER of the newest smallest value.
3. In the first for loop (after the second for loop finishes), you set the new array's value at I to the
old array's value at temp.
Ex: arraynew[i] = arrayold[temp];

How to do a bubble Sort
A: A bubble sort works by repeatedly swapping adjacent elements if they are in the wrong order (good
for if you need ascending or descending)
To do:
1. We have an array of size n, which means we need to do n-1 iterations. Each time we go over the
array, one set of elements will be sorted.
2. Steps: run a loop over the entire array, compare the element at index i with the element at i+1,
if I is greater than the element at i+1 swap both elements, else move on to the next element
begin bubbleSort(list)
for i = 0 to sizeof(list) - 1
for j = 0 to sizeof(list) - i - 1
if list[j] > list[j+1]
swap(list[i], list[i+1])
end if
end for
end for
end bubbleSort
From <https://www.scaler.com/topics/data-structures/bubble-sort/>
Linear Search:

The simplest approach to search for a specific element in a data set. It examines each element
until it finds a match, starting at the beginning of the data set until the end. The search is
terminated once the target is located.

Know how to do this. Did it on the project. Just remember the term definition.
Encapsulation:

A way to restrict the direct access to some components of an object, so users cannot access
state values for all of the variables of a particular object. Is used to hide both data members and
data functions or methods associated with an instantiated class or object.

Ky ideas: hide data (users don't know how classes are being implemented or stored. Only how
they are passes and initialized), flexibility, and reusability

Example: building computer. Just need to know how to use the parts and not how they work

Association: general binary activity that describes activity between two classes
Inheritance:

Allows one class to gain the properties of another class (like how a child inherits a parent's
genes). Allows programmers to create a new class that reuses the data members and methods of
an existing class

Define a general class (superclass) and extend to more specialized classes(subclass)

Syntax for subclasses:
SubClassName extends SuperClassName
Data types:

Protected: can be accessed from a subclass but not in a different package. Use if field intended
for extenders of the class but not users.

Private: can be accessed only from inside of the class. Not intended for users

Public: accessed from anywhere. Intended for users.

Void: no return

Static: global but can only be accessed from other static methods

Anything that is 'final' cannot be altered or extended. This counts for classes, methods, and data
fields. Final classes are useful for if you plan for other programmers to use your work. Basically if
they see final they can be like "I expect this class to always behave in this way" while looking at
it's usage in the code. No manipulation of it

So like, say we're working with shapes. We have a general class for things like color, fill, and
dateCreated. These apply to ALL shapes, so it's the superclass. Yet, not all shapes are the same.
So now we have an extension class for different shapes. Let's say a circle as an example. A circle
will extend from shape to inherit the previously mentioned functions (through the extend key)
and be filled with methods only relevant to the circle. Examples being get radius, get diameter,
get area, get perimeter.

A superclass can have many subclasses. For example, the shape class can extend to other shapes
like rectangle, square, polygon, etc. These can be filled with their own methods like get area, get
perimeter, get side count etc (yk bc the formulas for these things are different for all shapes)

A subclass can only belong to one superclass

Constructors of a superclass are not inherited by a subclass. They can only be invoked by the
keyword super. Use the super() or super(arguments) key to constructors from the super class.
Use super.methodName(parameters) to reference a method from the superclass

Constructor chaining: a superclass may be derived from another class. In this case, a superclass
invokes it's parental constructors before preforming it's one. This creates an inheritance
hierarchy (works down the chain).

Overriding :to override, the method must be defined in the subclass using the same signature
and return type as in the super. Since subclasses inherit superclass methods, sometimes you
need to modify the implementation of one of these methods for a specific subclass. Static
methods can't be overridden.

Overloading: define multiple methods with the same name but different signature(parameter list
in the parentheses).

Use the @overide and @overlode annotations to avoid errors and detect problems
Polymorphism:

A variable of a supertype can refer to a subtype object

Other words, an object of a subclass can be used wherever the superclass object is used. This is
implemented along the inheritance chain. Example being that a method is defined in a
superclass and overridden in a sublcass
Difference between data types:
Object classes:

EVERY CLASS IN JAVA IS DESCENDED FROM THE JAVA.LANG.OBJECT CLASS. I.e every time you
make a class, it's actually an extension from the overheading object class which is a super
Primitive concepts, relation to objects, and wrapper classes:

Primitive types aren't objects and need to be 'wrapped' using the wrapper class to be used.
There is a wrapper class for each primitive type (Ex: Character class for char, Double class for
double etc.)

Primitive wrappers are located in java.lang.(primitive type);

Construct wrapper wither with the primitive type's val in parentheses or the val as a string in
parentheses

Syntax ex: Integer intObject = new Integer(2);

Wrapper classes lack no-arg constructors

Converting a primitive value to a wrapper is called boxing. Reversing it is unboxing. Can be done
automatically

Wrappers contain the following methods:
+MAX_Value
+MIN_Value
+Integer(either an value:int or s: String)
+byteValue()
+shortValue()
+intValue()
+longValue()
+floatValue()
+doubleValue()
+compareTo()

Returns either 1(greater than) 0(equal to) or -1(less than)
+toString()
+valueOf()
+parse___()

The BigInteger and BigDecimal classes allow you uto exceed the maximum length of storage for a
primitive value (ex: lets a long store more than 7 bytes)

We can't normally alter strings, but when strings are wrapped as objects we can alter them
1. Java.lang.String;
+replace() -returns a new string that replaces all matching chars in the old string with the new entered
char
+replaceFirst() - replaces first matching substring with new substring
+replaceAll() replaces all matching substrings with the entered substring
+split() - returns an array of strings consisting of the substrings split by the delimiter
Files

Contains methods s for obtaining the properties of a file/directory and for renaming and deleting
a file/directory

To permanently store the data created in a program, you need to save them in a file on a disk or
other permanent storage device

The File class contains the methods for obtaining file and directory properties and for renaming
and deleting files and directories. However, the File class does not contain the methods for
reading and writing file contents

The File class is a wrapper class for the file name and its directory path

Do not use absolute file names in your program. If you use a file name such as
c:\\book\\Welcome.java, it will work on Windows but not on other platforms. You should use a
file name relative to the current directory

Use the Scanner class for reading text data from a file and the PrintWriter class for writing text
data to a file

There are two types of files: text and binary. Text files are essentially characters on disk. We
introduce how to read/write strings and numeric values from/to a text file using the Scanner and
PrintWriter classes

The java.io.PrintWriter class can be used to create a file and write data to a text file. First, you
have to create a PrintWriter object for a text file as follows:

PrintWriter output = new PrintWriter(filename);

Then, you can invoke the print, println, and printf methods on the PrintWriter object to write
data to a file
Methods:
+File - creates a file object for the specified path name
+exists - returns true if the file in the represented directory exists
+canRead() - returns true if the file exists and can be read
+can Write() - true if file exists and can be written to
+isDirectory() = true if the file represents a directory
+isFile() - if object represents a file
+isAbsolute() - file has an absolute path name
+isHidden() - file represented is hidden
+getAbsolutePath()- returns complete absolute file or directory name
+getCanonicalPath() - same as prior but removes redundant names and is presented as symbolic links
+getName()- returns the last name of the directory and the complete file name
+getPath() - returns the complete directory andfile name
+getparent() - reeturns complete parent directory
+lastModified() - returns tim elast modified
+length(0 - returns fil elength h
+listFile() - returns files under the named directory
+delete() - deletes file
+renameTo() - renames thefie
Throwing and Catching

InputMismatchException - wrong datatype where computer expects another

Exceptions are thrown from a method and the caller of the method can catch and handle the
exception (error happens and method catches it. But instead of terminating it prompts the user
to correct it and try again)

There are different exception classes that you can throw for the compiler to catch. When an
exception is thrown, it interrupts normal execution until it is bypassed
Exs:
ClassNotFoundException,
IOException,RuntimeException,ArithmeticException,NullPointerException,IndexOutOfBoundsexception,Il
legalArgumentException

To throw, we use a 'try' and 'catch' block. The try block contains the code that is executed if
normal. The catch block contains the exception along with code used to handle the exception.

The throwable class is the rood of exceptions. All inherit directly or indirectly from Throwable

Unlike a method, after the catch is executed it does not return to the throw statement to
execute throw code. It instead moves to execute the statement after the catch block

Exception types: System errors, exceptions, and runtime
Syntax:
Try {
Code to run;
Statement or method that may throw an exception;
More code
} catch (type name) {
Code to process the exception(exception handler)
}
…have as many catch blocks as you do exceptins types for the try block
Optional:
finally {
}

Exceptions are objects and objects are defined using classes. The root class for exceptions is
java.lang.Throwable

To declare an exception method
Public void myMethod() throws 'typeofexception'
If method may throw multiple exceptions add a list of them separated by commas

The finally clause executes whether an exception occurs or not and even if there is a return
statement prior to it

Chained exceptions: throwing an exception along with another exception

You can define custom exception classes by extendin the java.lang.Exception class
Download