Intro to Java Final Exam Review Guide and Course Summary PDF

Title Intro to Java Final Exam Review Guide and Course Summary
Course Introductory Programming in Java
Institution Johns Hopkins University
Pages 27
File Size 1009.6 KB
File Type PDF
Total Downloads 80
Total Views 169

Summary

This document summarizes all the content of the entire course, going into depth about java programming. It includes explanations of every concept in the course, as well as plenty of examples and is a very long document. Using this, a student was able to get an A on the final exam....


Description

Wk 1: basics Computer parts ● Hard drive stores data = grocery store ● RAM temp stores it = pantry ● Processor uses RAM = stove ○ P uses RAM b/c faster than using HD. can’t just use RAM w/out HD b/c RAM loses memory when turned off and has less avail space ○ Reads binary Programming languages: high to low level: pseudo > high > assembly > machine ● High level ○ Scripting: python perl javascript ○ Object oriented: C# C++ Java ○ Math: matlab, R ○ procedural/structured: C, Fortran, BASIC, Pascal ● Assembly ○ Java bytecode for JVM ● Machine ○ Binary ○ Machine code ○ Executable code High level → compiler converts code into executable form→ lower form → interpreter translates while running program Java compiled by Javac to bytecode → interpreted and run by JVM java virtual machine Why is java universal? ● For most languages, compiler’s executable only works on specific processor ● Javac compiles Java into a special portable executable, bytecode, that works on many dif devices. Each device has its own JVM which can execute/interpret bytecode Programming phases ● Define & analyze, design, write code, test code, documentation, maintain/upgrade 3 types of program control ● Sequential (default) ● Decision ● Repetition (loops) ● ALL general purpose programming languages must have ways to do these 3 things Sample run: what appears on the screen, including system printed output and your input Pseudocode: non-coding version of code Pseudocode tracing: following through pseudocode on paper

Incremental approaches to writing code ● Make subroutines/methods ● Top down ● Bottom up

Wk 2: primitives and order of operations Data types ● Primitive variables ○ Boolean ○ Byte: holds integer in one byte = 8 bits ○ Char: assigned a unicode value ■ 0 to 9 = 45 to 57 ■ A to Z = 65 to 90 ■ a to z = 97 to 122 ○ Short, int, long ■ Converted to binary; leftmost bit is for sign. ○ Float, double ■ Float has f @ end. E.g. 10f ■ Double can be float or scientif notation ● Collections of similar data: string, list (1d array), table (2d array) ● Objects Order of operations 1. () 2. - negation, casting: (int) (double) etc. 3. *, /, % 4. +, 5. = Types of processing ● Structured: input data, process, produce output (sequence, decisions, loops) ● Procedural: pass data, process, return values ● Object oriented: define data attributes and methods that operate on them, creating powerful new data types At least one class in the project (set of classes) MUST have a main method Identifiers ● class/method/variable names ● Can contain: letter, $, digit. but digits cannot be first char Escape sequences ● \” ● \\ ● \n ● \t Use final for constants whose values do not change

+=, -=, *=, -= ++ and -● Remember prefix vs postfix ● Int x = 5 ● Int y = x++ ○ Y is 5 and x is now 6 ● Int z = ++y ○ Y becomes 6 and then z set to 6 JAVA API: set of pre-existing java software; sometimes need to be imported Java.lang classes are always implicitly included Method calls ● Static method = does not have to be instantiated. Simply called ○ methodName(params) if in same class ○ ClassName.methodName(params) if in dif class ■ E.g. Math.round(value) ● If belongs to object ○ objectVar.methodName(params) ■ E.g. System.out.println(“hello”); ■ E.g. myString.charAt(0);

● ● ● ● ●

Wk 3: strings and scanner, casting If you add anything to a string, result is a string ○ E.g. System.out.println(5 + “ “) results in a string output String s = “potato”; ○ S is a reference variable to where the string is actually located Character indice starts at 0 S = “this” + “string” combines the two words into one string Useful methods ○ string.charAt(index) ○ string.indexOf(char) ○ string.length() ○ string.substring(index) ■ This provides the substring from the index to the end

■ ■



○ ○ ○ ○ ○ ○ ○ ○

○ ○

There’s an invisible character after the last item in a string so if you do substring (indexOfItemAfterLast) you get a blank

● string.substring(start, end+1) ■ Substring by default goes up to the end - 1 so if you want from 1 to 5, use substring(1,6) string.toLowerCase() string.toUpperCase() Integer.parseInt(string) converts string to integer Double.parseDouble(string) To convert primitive to string, do this: number + “” string.isEmpty() String2 = string1.concat(“ABC”) ■ Saves the contents of string1 with ABC on the end to string2 String3 = string1.replace(“A”, “a”) ■ Saves the contents of string1 with all instances of A converted to a to string3 string.equals(string2) string.equalsIgnoreCase(string2)



● ●

○ string.compareTo(string2) ○ string.compareToIgnoreCase(string2) Scanner methods ○ *note* the next… methods except nextLine skip all spaces, tabs, and newlines to get the next item ○ next() ○ nextInt() ○ nextDouble() ○ next().charAt(0) ○ nextLine() ■ Does not include the end-line character ■ If the stream is at the end of a line when you start reading, nextLine saves an empty string and the stream moves to the next line String1 == string2 compares the reference variables and locations in memory ○ string.equals(string2) compares the contents of the strings Character methods. These are in the Character class and must be prefaced with Character. ○ E.g. char apple = ‘a’; ○ isLetter(apple) returns true ○ isDigit(apple) returns false ○ isWhitespace(apple) returns false ○ toUpperCase(apple) returns a character ○ toLowerCase(apple) returns a character

Java data types ● Built in primitives: data stored directly in memory location associated with variable ● Objects (reference variables): arrays, API library, user defined classes, variables contain references to objects in memory where actual data is stored; methods act on data in the objects whereas they make copies of primitives that are passed to them



● ●

Wk 4: decisions Switch format ○ switch (variable) { ○ case c1: ■ Statement ■ Statement ■ Break; ○ case c2: ■ Statement; ■ Statement; ■ Break; ○ default: ■ Statement: ■ Statement: ■ Break; ○ Can have multiple cases on one line:

■ false && false → returns false3 Demorgan’s laws - can just memorize this but explanation below also ○ ! (A && B) == !A || !B ○ E.g. ■ A = true if raining and B = true if cold ■ It’s raining and cold right now ■ So the left side is false ■ Not raining and not cold results in false on right side also ■ Right side: not either of two things means both things must be false ○ ! (A || B) == !A && !B ■ This is only true if the right side is computed before the left side ■ That’s why we usually put () around it ■ Since == has precedence over &&, the left side ends up getting compared to !A instead of the entire side and then it does && !B which makes the whole thing false ● ! (A || B) == !A && !B → false ● ! (A || B) == !A → true ● !B → false





● So if you do ! (A || B) == !A and then && !B, answer is false ● But ! (A || B) == (!A && !B) → true ○ How to remember: ■ Remember the basic structure ■ Swap the || and && Order of operations - MEMORIZE THIS ○ () ○ - negation, ! not, casting, ++, -○ *, /, % ○ +, -, + concat ○ , = ○ ==, != ○ && ○ || ○ =, *=, %=, etc. Testing ○ Whitebox: test each piece of code thoughtfully ○ Blackbox: throw lots of dif inputs at it ○ Regression: test incrementally as you code ○ Unit: individually test each method with its own mini driver program. Use whitebox testing



Wk 05 Two types of loop designs ○ Counter controlled: certain number of times ■ For loop ● Checks the condition AFTER running once - see practice quiz, question #7 ○ Sentinel controlled: until event/value occurs ■ While ● Checks the condition before running ■ do/while ● Does the do statement and then checks condition, then returns to complete those statements if while condition is met ● I.e. always runs at least once ● E.g. ○ do { ○ System.out.println(“picasso”); ○ } ○ while (x < 5); ● Notice that the “while” line has a semicolon at the end ■ E.g. run until your run out of input

E.g. while loop for which the initial condition is not  met Code: int x = 1 do { System.out.println("picasso's paintings"); System.out.println(x); x--; } while (x > 1); Output: picasso's paintings 1

● ● ●



● ● ●





Wk 06 If “return” is encountered, the method immediately ends. No statements after the method return are compiled or encountered Static methods can be called without being instantiated When passed to methods ○ Primitives are copied ○ Objects’ addresses are passed so they are directly acted on Lifetime: duration variable exists in memory; from declaration to end of execution of its enclosing block ○ Lifetime continues if control is passed to another method (i.e. the current method is on pause while the other method runs) Scope: where variable can be used Variables with same name can be declared in separate blocks/methods UNLESS nested Math. ○ pow(number to square, power) ○ sqrt(#) ○ ceil(#) ○ floor(#) ○ round(#) ○ .PI ○ .E Wrapper classes: let you create an object of a primitive type ○ E.g. Integer object = new Integer(9) ○ The integer address will be passed to another method and thus the variable itself is acted upon rather than acting upon a copy Some non static methods ○ Random randy = new Random(); ■ Uses current time as seed ■ randy. ● nextInt() ● nextInt(N) - random int in range [0, N) ● nextFloat() - float 0 parameter ● Have “interface” in their title Upcasting ● Can cast a subclass to the superclass type ○ E.g. Animal a = new Cat(); ○ Cat is a subclass of Animal and gets upcasted to type Animal so that “a” is a type of Animal with all the methods/data types of Cat ● Upcasting is implicit ● Maybe have other methods, etc. that only work on Animal type but want the methods of Cat, etc. Downcasting ● E.g. Animal a = new Animal(); ● ( (Cat)a).makeSound(); ○ This statement casts a to type Cat (explicitly) and then calls the Cat version of the method ● This allows us to use the Cat and Animal versions of the method for “a” whenever we want Implicit conversions ● E.g. MyFace is an interface ● To implement MyFace in MyBase ○ MyFace face = new MyBase(); ● If MySub is another class and we want to extend MyBase to it, ○ MyBase = new MySub(); ○ This automatically extends MyBase instead of implementing it because MyBase was never an interface to begin with ● General pattern: the thing that is extended or implemented goes on left of equals sign







Static methods can't access instance data. This is impossible because static methods are called on the entire class, not a particular instance, so there's no way of knowing which instance the programmer would to read or manipulate data from when calling static methods. Therefore, static methods have access only to static data. (Instance methods, on the other hand, act on data from the calling instance, as referenced by this.) As further noted below, instance methods can also access static data, so there are two things that need to be changed for the original statement to be true.

Wk 12 Recursion: method repeatedly calls itself vs Iteration: method uses loop(s) without repeatedly calling itself Recursion: break problem into small pieces and repeat small piece many times Recursive method must have ● Recursive cases - calls itself ● Base cases - after repeatedly calling itself, this is the default value at the end of the rabbit hole E.g. fibonacci calculator, where n = # of months n: 1 2 3 4 5 6 f: 1 1 2 3 5 8 ● f is: ○ 1 if n = 1 or 2 ○ f(n-1) + f(n-2) for n > 2 ● So recursive method is: ○ public static int fibonacci(int n) { ■ if (n == 1 | n == 2) { ● return 1; ■ } ■ else { ● return fibonacci(n-1) + fibonacci (n-2); ■ } ○ } BUT recursive methods require extensive periods of time. If you did fibonacci(6) it would be f(6) = f(5) + f(4) = f(4) + f(3) + f(3) + f(2) = ...etc. Array operations Search ● Linear search: O(N) ● Binary search: O(logN) ○ Cut data set in half and then go in correct direction Sorting ● Insertion: consider each element and move it as far left as necessary ● Selection: start with leftmost value. Compare it to values going down the line. If you find a lower value, remember it, and continue going left. Once done going through list, swap original number with lowest value. Now lowest value is on the left. Then redo for all values except the new leftmost ● Bubble: compare adjacent values, usually going left to right and end up with max value at end of row in one iteration ● Merge: split data in half → split each half into smaller pieces until single values → in each of the og halves, arrange each pair of numbers from low to high and then combine

each pair, putting numbers in low to high, and so on

Sorting efficiencies: ● Bubble / insertion / selection (bis) ○ O(N2) ● Merge ○ O(N log N) ○ Always better than bis

Wk 13: Error handling Great video - https://www.youtube.com/watch?v=EWj60p8esD0 Error types ● Illegal casting conversions - e.g. int x = 34.0 ○ Cannot implicitly convert double to int ● Bad indices, out of bounds ● Illegal data types, e.g. “ten” instead of 10 - usually due to user error ● File not found ● Null pointer exception - when the object the code references is null I have no idea what the slides on exceptions are referring to so here are notes from online first: ● Exception: error that occurs in program execution, causes execution to end ● Exception handling: handling exceptions gracefully so that exceptions do not end program execution Syntax for error handling Try and catch ● try { ○ //some statemenets ● } catch (Exception e) { ○ // some code to handle errors ○ } Catch: declare the type of exception you are trying to catch in () If an exception occurs in the try block, the catch block that follows the try block is checked If the type of exception that occurred in the try block matches the type of exception in the catch statement, then the catch statements occur. Catch acts similar to a method, receiving Exception as a parameter Exception e: catches all possible exceptions Multiple exceptions ● Try and catch: the point is to handle the error if it occurs or print an error message; if try statements have an exception and the exception type is matched by the catch right after the try, then do the statements in the catch to fix the error/print to tell us about it



E.g.



○ Multiple exceptions Throw: the point of throw and throws is to print a custom-user error message for a certain exceptionlets you manually generate exceptions from methods; in the method definition; defines the type of exceptions the method can throw ○ Throws is for checked exceptions: declares that the method in question throws the specified checked exception ○ Unchecked exceptions can be thrown without having to declare throws in the method header but this is unnecessary/bad practice ○ Throw: the actual instruction to throw the exception ■ Throwable: a class you must extend in order to create your own, custom, throwable



○ ○ ○

Throw: corresponds to the exception in the header and has a custom message To have multiple exceptions, use a comma-separated list after “throws”







E.g.

e.g. ■ Notice how it says “new Arithmetic…” ■ Because exceptions are objects Throws also lets you use another method to handle the exception ■ Can add throws… to a method header and then put that method’s execution in the try portion of a try/catch block



E.g.

Two types of exceptions ● Checked: checked when compiled ○ There’s something wrong with the way the code is written such that it won’t even get to the execution stage ○ Represent invalid conditions in areas outside the immediate control of the program - often invalid user input, file missing ○ You must establish a fix using a try/catch block ● Unchecked (also called “runtime”): checked when run (interpreted/executed for java) ○ E.g. dividing by 0 ○ There’s nothing wrong with the code as written ○ But when the code is actually executed it encounters an error ○ Represent defects in the program(bugs), often invalid arguments passed to a non-private method ○ You don’t need to establish a policy for them

Back to the class notes: ● Exceptions are objects ○ Indicate error situations



When exception thrown from within a try block, can be caught and handled by catch OR let the program crash ● Throwable (base of exception hierarchy)’s methods are inherited by other exception classes ○ Throwable(), Throwable(String msg) ○ getMessage() ■ Specific types of errors have built-in error messages in java. You could do System.out.println(e.getMessage()); inside a catch block and it would print the type of error to the screen. E.g. for div by 0: ● “/ by zero” ○ toString() ■ Similar to getMessage, this prints out the long java name for the type of exception. E.g. for dividing by 0, System.out.println(e.toString()) might print ● “java.lang.ArithmeticException…” ○ printStackTrace(), printStackTrace(PrintWriter) ■ E.g. “e.printStackTrace” in the catch block prints an even longer message for the type of error. This is the regular message that java would print when you have an error ● Exception extends Throwable ● Most of these are unchecked - related to runtime ● Checked exceptions usually related to IO Unchecked: ● RuntimeException extends Exception ○ ArithmeticException extends RuntimeException ○ IllegalArgumentException extends RunTimeException ■ NumberFormatException extends IllegalArgumentException (parsing from String) ○ Array/String Index out of bounds ○ Null pointer exception ○ Input mismatch exception - scanner Checked ● IOException ○ FileNotFoundException extends IOException The final has questions that ask to identify unchecked vs checked. Remember that ● Checked is almost always IOExceptions ● Unchecked includes everything wrong with the code running. If the error is fine as written and the code can compile BUT NOT run, then it is unchecked ○ E.g. null pointer exception is fine as written but the actual running presents an issue Exception handling ● Exceptions are objects



There are already many exception classes in Java API, which all have Throwable as the base ● We can create our own exception classes also ● To use exceptions: ○ Create a try block with statements to try ■ Create exception block(constructor call) inside ■ Throw an exception object ○ Catch an exception object to handle gracefully ○ Use finally clause to execute code no matter what ● If operation “throw”s an exception that isn’t caught, program will stop and printStackTrace ● To declare exceptions: throws particularException ○ Needed for checked exceptions(compiler checks) Example: errorStuff.java

When you input a = 2, you get this:

So printStackTrace showed the error but the code kept executing ● ●

So it seems checked exceptions use throws and throw And try/catch is for unchecked...


Similar Free PDFs