Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- _/_/ _/_/_/ _/_/_/ _/_/_/ _/ _/_/
- _/ _/ _/ _/ _/ _/_/ _/_/_/ _/_/ _/_/_/ _/ _/_/_/ _/ _/
- _/_/_/_/ _/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/_/_/_/
- _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/
- _/ _/ _/ _/_/_/ _/_/ _/ _/ _/ _/_/_/ _/_/_/ _/_/_/ _/ _/ _/
- _/
- _/
- AP Computer Science A -- In-Class Notes, Valley High School, 2010-2011
- Taught by Dave Cochran, taken by Will Crichton
- These notes are best read in Notepad++ (search the interwebs if you've never heard of it) with Java syntax highlighting.
- Not all concepts taught in class can be listed here, due to either the use of visual aids such as diagrams or the laziness of the author.
- The author was gone for some of the lectures due to extracurricular activities, as noted in the comments.
- Font: JS Stick Letters
- ___ __ ___ __ ___ __ __ ___ ___ ___ __
- | /\ |__) | |__ / \ |__ / ` / \ |\ | | |__ |\ | | /__`
- | /~~\ |__) |___ |___ \__/ | \__, \__/ | \| | |___ | \| | .__/
- I. Object oriented programming
- II. Basics of Java programming
- a. Variables
- b. Typecasting
- c. Operators
- d. If statement
- III. Looping structures
- a. Repeat-until
- b. For loop
- IV. Arrays
- a. 1-D arrays
- b. 2-D arrays
- c. ArrayLists
- V. Methods
- a. Using methods
- b. Declaring methods
- VI. Classes
- a. Client classes
- b. Wrapper classes
- c. Author classes
- d. Example ATM class
- VII. Recursion
- */
- /* __ __ ___ __ ___ __ __ ___ ___ ___ __ __ __ __ __ __ __
- / \ |__) | |__ / ` | / \ |__) | |__ |\ | | |__ | \ |__) |__) / \ / _` |__) /\ |\/| |\/| | |\ | / _`
- \__/ |__) \__/ |___ \__, | \__/ | \ | |___ | \| | |___ |__/ | | \ \__/ \__> | \ /~~\ | | | | | | \| \__>
- Objects are a data structure that contains methods (functions) to use on the data structure
- Inheritance -- you get to use all the method of your "super" (or parent) class
- i.e. if your parent is an integer, then if you inherit the methods of an integer, then you can use them in your own class
- Encapsulation -- data security! By making methods "private", outside programs cannot access the values within it
- Only way to acesss private methods is either A. writing them yourself or B. using public methods that access the private methods
- Polymorphism -- keeping "ways" of doing things similar
- */
- /* __ __ __ __ __ ___ __ __ __ __ __ __
- |__) /\ /__` | / ` /__` / \ |__ | /\ \ / /\ |__) |__) / \ / _` |__) /\ |\/| |\/| | |\ | / _`
- |__) /~~\ .__/ | \__, .__/ \__/ | \__/ /~~\ \/ /~~\ | | \ \__/ \__> | \ /~~\ | | | | | | \| \__>
- Programs can be created from two perspectives:
- 1. client, which is other people's work (i.e. java.lang, java.util)
- 2. author, you -- the original code
- Everything is a CLASS
- - client program always has the "main" method
- - author program has no "main" method
- In Java, the class name and the file name are the same.
- Rules for naming variables are the same as BASIC, but now you can use reserved words (i.e. boolean or for)
- Public vs. Private — public variables can be accessed by anyone, whereas private variables are only accessed by the class
- Syntax for declaring classes: [public OR private] class [identifier] { }
- Syntax for declaring methods: [public OR private] [static?] [return type] [identifier] ( [params] ) { }
- Static means that it makes a memory location before execution that contains a SINGLE value
- */
- public class HelloWorld {
- public static void main(String[] args){
- System.out.println("Hello, World!");
- }
- }
- /*
- II-a. Variables
- Identifiers can be lots of things!
- - Variable
- - Array name
- - Class name
- - Method name
- Primitive data types (only a single value, no methods that come with it):
- boolean - 1 byte = false/true
- char - 2 bytes (unicode)
- int - 4 bytes, ±2^31
- double - 8 bytes, ±1.8 * 10^308
- ——————
- byte - 1 byte, ±128
- short - 2 bytes, ±32767
- long - 8 bytes, ±2^63
- float - 4 bytes (single), ±3.4 * 10^38
- How to declare a variable: [type] [identifier]
- */
- int intX = 50;
- double dblAverage = 0.3;
- boolean boolTest = true;
- char chrLetter = 'F';
- int intA, intB, intB = 5;
- /*
- II-b. Typecasting
- Scope - part of the program in which the value is valid
- Declaring a value inside a set of braces (i.e. a for loop, function) means it can only be accesed from within that set of braces
- Assignment statement: [identifier] = [expression]
- addition +
- subtraction -
- multiplication *
- division /
- remainder %
- math.pow (function for exponentiation)
- Typecasting — to change the primitive type of a result
- */
- int intX = 8 / 3; // intX now = 2
- double dblY = 8 / 3; // dblY = 2
- double dblY = 8 / 3.0; // dblY = 2.67.
- double dblY = (double) (8/3); // dblY = 2.0
- double dblZ = (double) 8 / 3; // dblZ = 2.67
- // Output: use the nice little System class
- System.out.println("Hello, World!"); // prints a whole line (inserts \n character)
- System.out.print("Howdy, Earth!"); // just prints it, keeps going on same line
- /*
- II-c. Operators
- Expresion Operators
- greater than is >
- less than is <
- greater than/equal to is >=
- less than/equao to is <=
- equal is ==
- not equal is !=
- and is &&
- or is ||
- not is !
- Not operator distributes... so !(a || b) is !a && !b
- a+=b same as a = a + b
- a-=b same as a = a - b
- a*=b same as a = a * b
- a/=b same as a = a / b
- a%=b same as a = a % b
- a++ same as a = a + 1 (++a similar, but evaluates the 1 first?)
- a-- same as a = a - 1
- */
- boolean a;
- int x, y;
- a = x < y;
- /*
- II-d. If statements
- You don't necessarily need braces, but it's required for multiple statements.
- if ( condition )
- statement;
- if ( condition ){
- statement1;
- statement2;
- statement3;
- }
- if ( condition )
- statement1;
- else
- statement2;
- if ( condition ){
- if ( condition2 ){
- statement1;
- }
- } else {
- statement2;
- }
- */
- if ( bIsTrue ){
- bIsTrue = !bIsTrue;
- System.out.println( "The boolean is true! (but now it's false)" );
- }
- /* __ __ __ __ __ ___ __ __ ___ __ ___ __
- | / \ / \ |__) | |\ | / _` /__` | |__) | | / ` | | | |__) |__ /__`
- |___ \__/ \__/ | | | \| \__> .__/ | | \ \__/ \__, | \__/ | \ |___ .__/
- Repeat-Until: While: For:
- Init Init Init
- Increment Step Step
- Body Body Body
- Step Increment Increment
- Exit Exit Exit
- While loop syntax:
- while( condition )
- statement;
- */
- while( x == true ){
- y++;
- a *= b + c;
- }
- /*
- III-a. Repeat-until
- Repeat-Until loop syntax:
- do {
- statement;
- } while ( condition );
- */
- do {
- a %= b * c;
- System.out.println("Hello, World!");
- } while ( y == true && d == false );
- /*
- III-b. For loop
- For loop syntax:
- for ( init; step; increment ){ code; }
- */
- for( int i=0; i<10; i++ ){
- things;
- }
- /* __ __ __
- /\ |__) |__) /\ \ / /__`
- /~~\ | \ | \ /~~\ | .__/
- IV-a. 1-D arrays
- Arrays are objects (not primitive types). They hold multiple variables. In Java, arrays can only hold values of a specific type (i.e. int)
- Declaring an array:
- TYPE IDENTIFIER []
- */
- int aNumber[];
- aNumber[5] = 10;
- int num1[], num2[];
- int [] num1, num2;
- int values[] = new int[15];
- int numbers[] = { 19, 23, 74, 58, 6 };
- String names[] = { "John", "Mary", "Fred" };
- for( int intLoop = 0; intLoop < names.length - 1; intLoop++ )
- System.out.println(names[intLoop]);
- /*
- IV-b. 2-D arrays
- I missed this day's lecture.
- As you would expect, 2-D arrays are just arrays of arrays. Simple BASIC stuff. Main thing different is how to initialize.
- TYPE IDENTIFIER[][] = new TYPE[BOUND1][BOUND2]
- */
- int NumArray[][] = new int[5][4];
- int Array1D[] = new int[4];
- Array1D = NumArray[1]; // Note: this assignment duplicates the values in NumArray[1] into Array1D, it doesn't create a pointer (meaning changing NumArray[1] does not change Array1D)
- int[][] changeArray( double[][] myArray ){ } // Declaring a method with both a 2-D return type and passing 2-D array as a parameter
- /*
- IV-c. ArrayLists
- I missed this day's lecture.
- ArrayLists are basically arrays which don't have a defined length.
- Also, ArrayLists are strictly objects, so you treat them like you would any other object (use methods on them).
- */
- import java.util.ArrayList;
- ArrayList<Object> list = new ArrayList();
- list.add("Hello!");
- list.add(new Double(5.2));
- System.out.println(list.size());
- // Common methods: add, get, indexOf, remove, size
- /* ___ ___ __ __ __
- |\/| |__ | |__| / \ | \ /__`
- | | |___ | | | \__/ |__/ .__/
- V-a. Using methods
- Classes have constructors, and then methods
- To use have methods, you do: identifier.method(PARAMETERS);
- String class! You should know the following methods:
- int length()
- String substring(int from, int to)
- String substring(int from)
- int indexOf(String str)
- */
- String word = "ABCDEFGHIJK";
- word.length() // is 11
- word.substring(8) // is IJK
- word.substring(5,8) // is FGH
- word.indexOf("CDE") // is 2
- /*
- V-b. Declaring methods
- Declaration syntax:
- [private OR public] [return-type] [identifier] ( [parameters] ){ }
- Methods are generally going to be public.
- Return types will be of a primitive type (boolean, int, etc.), an object type (Integer, String, etc.), or a void type (returns nothing)
- Parameters are set with ([type] [identifier], [type] [identifier], ...)
- Remember ByVal and ByRef? Parameters in Basic were passed either by creating a copy of the value or pointing to the original value.
- In Java, all primtitve values are passed by value -- a duplicate is made.
- All object parameters are passed by reference.
- */
- public double AveFind( int[] numArray ){
- double dReturn = 0;
- for(int i=0;i<numArray.length;i++) dReturn += numArray[i];
- return dReturn / numArray.length;
- }
- /* __ __ __ ___ __
- / ` | /\ /__` /__` |__ /__`
- \__, |___ /~~\ .__/ .__/ |___ .__/
- VI-a. Client classes
- These classes often come in packages -- i.e. java.lang, java.util, java.text
- Rather than grabbing outside code every time you use it, Java allows us to establish a link to packages to use in the rest of the program.
- This is done through the use of the "import" statement.
- */
- import java.text.*; // imports all of java.text
- /*
- java.text is used to format the OUTPUT of values, like numbers and such.
- It does not affect the value itself, but rather how it appears in the console -- i.e. converting numbers to dollars and cents.
- Useful function: "format"
- */
- import java.text.DecimalFormat;
- DecimalFormat moneyFormat = new DecimalFormat("0.00");
- String moneyAnswer = moneyFormat.format( 32.5255 ); // 32.53
- /*
- VI-b. Wrapper classes
- Wrapper classes change a primitive type into an object.
- Generally, we use the wrapper classes Integer and Double.
- More specifically, you'll use the toString and intValue/doubleValue methods in those classes.
- These are useful for storing and retrieving primitive types in object arrays.
- */
- Double dValue = new Double(5.00);
- dNum = 3.0 * dValue.doubleValue();
- /*
- VI-c. Author classes
- Classes are like cars, except less flashy and they don't use gasoline. They're vehicles for the values and methods you want to use.
- Difference between classes you've made so far is there's no "main" method, meaning the class is not executable by itself.
- Classes are divided into two areas, the "private" section and the "public" section.
- The private sector contains values and methods only accessible by the class itself -- encapsulation
- Generally, the private sector contains data (i.e. your credit card number or PIN number)
- The public sector can be accessed by anyone. It has:
- Constructors -- how you tell the compiler that you want to create a space in memory for this object
- A default constructor initalizes all variables to nothin'.
- You can have multiple constructors with different parameters (i.e. passing an int or a String for some reason)
- Accessors -- how you access data, typically begin with "get", i.e. obj.getValue();
- Modifier -- change the data in the object, typically begin with "set", i.e. obj.setValue(param)
- Overload -- take an existing symbol or method and change its execution
- For this class, you write three programs for each class-based project.
- 1. The class itself -- the class, variables, methods, etc.
- 2. The tester program -- test EVERY SINGLE method in the class for errors
- 3. The client program -- whatever you're trying to accomplish by using this class
- */
- // The author class
- public class Fraction {
- // Private variables
- private int myNumerator, myDenominator;
- // Private methods
- private Fraction reduce(){
- }
- // Constructors
- public Fraction(){
- myNumerator = 0;
- myDenominator = 1;
- }
- public Fraction(int a, int b){
- myNumerator = a;
- myDenominator = b;
- }
- public void fracOutput(){
- System.out.println(myNumerator + "/" + myDenominator);
- }
- public void setNumerator(int a){
- myNumerator = a;
- }
- public void setDenominator(int a){
- if ( a == 0 ) throw new Error("Denominator cannot be set to zero");
- myDenominator = a;
- }
- public Fraction add(Fraction x){
- return new Fraction(
- myNumerator * x.myDenominator + myDenominator * x.myNumerator,
- myDenominator * x.myDenominator
- );
- }
- }
- // The tester class
- public class FracTester {
- public static void main(String[] args){
- Fraction x = new Fraction();
- m.fracOutput();
- Fraction n = new Fraction(2,3);
- n.fracOutput();
- m.setNumerator(3);
- m.fracOutput();
- }
- }
- /*
- VI-d. Example ATM class
- To log in to an ATM, you scan your card and enter your PIN. The ATM uses some fancy math to find your bank account based on your card number.
- This process of creating card numbers from bank accounts is known as "hashing", which is the use of math operation(s) on a value to determine a second value.
- In this case, both your PIN number and account number are five digit prime numbers, and your card number is the two multiplied together.
- Things your ATM should do:
- Login
- Deposit
- Withdraw
- Balance summary
- Transfer
- Logout
- Add account
- Data members:
- Account number
- PIN number
- Login boolean?
- Checkings/savings
- Personal info (name, address, city, state, zip)
- Constructors:
- Default, zero for all values
- Assign all values
- Accessors:
- Get checking
- Get savings
- Get login info (account #, PIN #)
- Modifiers:
- Withdraw (watch for insufficient funds)
- Deposit
- Transfer
- */
- /* __ ___ __ __ __ __
- |__) |__ / ` | | |__) /__` | / \ |\ |
- | \ |___ \__, \__/ | \ .__/ | \__/ | \|
- Recursion is the reverse of iteration (iteration is looping, where you go from small --> large).
- In recursion, you go from large to small.
- Rules for recursion:
- 1. Must step the recursion
- 2. The problem MUST become "simpler"
- Famous recursive sequence: Fibonacci sequence. Each term in the sequence is the sum of the two preceding it.
- 1, 1, 2, 3, 5, 8, 13, 21...
- To get the 75th term,
- Issues with recursion:
- 1. Takes a lot of memory. Recursive methods call themselves within themselves (i.e. running method A runs method A again).
- */
- public int getFibo(int n){
- if( n == 1 || n == 2 ) return 1;
- return getFibo(n - 1) + getFibo(n - 2);
- }
- getFibo(4); // return getFibo(3) + getFibo(2)
- // getFibo(3) = getFibo(2) + getFibo(1) = 1 + 1
- // return 2 + 1 = 3;
- public int getFacto(int n){
- if( n == 1 ) return 1;
- return n * getFacto(n - 1);
- }
- getFacto(4); // return getFacto(3) * 4;
- // getFacto(3) = getFacto(2) * 3 = getFacto(1) * 2 * 3 = 1 * 2 * 3;
- // return 1 * 2 * 3 * 4;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement