AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive and Reference Variables Key words / Reserved words Naming Conventions Comments Assignment and Operands Date: 9/11/2017 Aim: Method Declarations Date: 9/14/2017 Aim: Calling Methods Date : 10/2/2017 Aim : Loops ( for ) & Decisions ( if ) for statement: if-then-else statement: Modulo operator (%): Relational Operators: Increment and Decrement: Error Types: Syntax and Logical Date : 10/12/2017 Aim : String Operations String Operations: Escape Sequences: Date: 10/17/2017 Aim: Math & Numbers (lesson 4) Multiple declarations The assignment operator Fundamental arithmetic operations PEMDAS Increment & Decrement Compound Operators Integer Division Truncation Date: 10/19/2017 Aim: Numbers: Mixed Data Types, Casting, and Constants (lesson 5) Mixed data types Casting Constants
Date: 10/25/2017 Aim: Boolean Operators (lesson 8) & Keyboard Input (lesson 7) Boolean Operators: Keyboard Input: String equality: Date: 10/30/2017 Aim: Switch & While (lessons 10 & 12) if versus switch Another if versus switch for versus while while versus do-while Compound Control Expressions More fun stuff Math.random( ); return; if (word.equalsignorecase( hello ))... char letter = word.charat(1); // returns e int offset = word.indexof( e ); // returns 1 int offset = word.tolowerc ase().indexof( h ); // returns 0 (zero) More java string methods: https://www.javatpoint.com/java-string
Date : 9/8/2017 Aim : Java Basics Why Java? Java is platform independent - it runs on any computer with a Java interpreter. Almost every browser includes a Java interpreter; therefore almost every computer can interpret Java code. MyProgram.java MyProgram.class My Program (Source code) (Java byte code) (Runs) Objects and Classes All code is written inside Classes We can create a penguin class Classes create Objects We can create penguins named Blackbeard, Bruce, Einstein, Gandhi, and Lindsey. These are all unique objects of the same class. Objects have Properties and Behaviors Properties define what the object has : hat, coat, beard, glasses, shoes, age, etc. Behaviors define what the object does : talk, write, ski, work, etc. Data types: Primitive and Reference Eight primitive data types exist as part of the Java language (we ll use the boldface data types): boolean - true or false byte - integer, 8 bits of storage char - single Unicode character short - integer, 16 bits int - integer, 32 bits long - integer, 64 bits float - decimal, 32 bits double - decimal, 64 bits Reference data types are user-defined classes created using primitive data types Many are available from the Java API library for general use Examples: String Scanner Random Math
Variables A Variable is a space in memory that stores a data value of a particular data type. Variables are used to store information which the program needs to do its job. Data types may be defined as a primitive type ( int ), or as an object type ( String ). Examples: boolean hat = false; String job = Scientist ; // double quotes char gender = f ; // single quotes Penguin huey = new Penguin( ); Key words / Reserved words These are words that mean something in Java, and they cannot be used to name anything else. Examples: boolean case class public for do Naming Conventions Naming conventions are not important to Java; they are important to programmers. Class names begin with Uppercase letters Method names begin with lowercase letters Variable names begin with lowercase letters All names MUST be descriptive and can be a combination of two or more words: the words are joined, but the start of each new word is uppercase (ie- typeofcar ) Java is CASE SENSITIVE ( cat!= Cat ) Comments Three types of comments: Single line: // comment, explanation, etc. Multiple line: /* * comment, etc */ JavaDoc (for Documentation Generator): /** * @param hat the type of hat */
Assignment and Operands Variables are assigned values using a SINGLE equal sign. char myinitial = W ; String thisschool = CMHS ; double addhalf +=.5; // same as addhalf = addhalf +.5; The right side is evaluated first, and the resulting value is stored in the variable. Operands: + - * / % (addition, subtraction, multiplication, division, modulo) Date : 9/11/2017 Aim : Method Declarations The method declaration requires modifier (public or private) return type name a pair of parentheses ( ) a body between braces { } public int addtwonumbers (int a, int b) { return a + b; } Date : 9/14/2017 Aim : Calling Methods p1.getname(); vs. getname();
Date : 10/2/2017 Aim : Loops ( for ) & Decisions ( if ) for loop: Repeats the statement(s) while a given condition is true. if statement: executes a section of code only if a test evaluates to true. else statement: a secondary path when an "if" clause evaluates to false for statement: // initialize the loop control variable for (initialization; BooleanExpression; update) { // Statements } // i is the loop control variable for (int i=0; i < 3; i++) { System.out.println(i); } Program Trace i i < 3 result 0 true 0 1 true 1 2 true 2 3 false if-then-else statement: if (condition) { // statements else if (condition) { // statements else if (condition) { // statements else { // statements if (grade==100) { letter = A+ else if (grade>=90) { letter = A ; else if (grade>=80) { letter = B ; else { // grade < 80 letter = C ; Modulo operator (%): Returns the remainder of two numbers: 1 R 2 12 % 10 = 2 10 )12-10 2 Often used to determine if a number is odd or even (if the number % 2 is 0 it s even) Relational Operators: < > <= >= ==!= Note: Equality contains TWO equal signs Not is always represented with an exclamation point
Increment and Decrement: Increment: add 1 long way: i = i + 1; abbreviated: ++i; i++; Decrement: subtract 1 long way: i = i - 1; abbreviated: --i; i--; Error Types: Syntax and Logical Syntax errors: Program won t compile due to errors with spelling, punctuation, etc. Logical errors: Program compiles but doesn t do what you want it to? Which one is harder to debug? Date : 10/12/2017 Aim : String Operations String Operations: Concatenation : Put one string at the end of another String x = hello + there ; Length : returns the # of characters in a string int c = s1.length( ); touppercase : s2 = s1.touppercase(); tolowercase : s3 = s1.tolowercase(); Substring: Extract a subset of a String: beginning at the OFFSET specified String s1 = Good Morning! ; // G o o d M o r n i n g // 0 1 2 3 4 5 6 7 8 9 10 11 String sub1 = s1.substring(3); // sub1 contains d Morning! beginning at the offset (inclusive), ending at the offset (exclusive) String sub2 = s1.substring(3,7); // 3,4,5,6 // sub2 contains d Mo Escape Sequences: Allows inclusion of special characters in a String String str = Say \ Hi\ to him. ; // str will contain: Say Hi to him. Sequence Inserts a \t tab \n new line \" double quote \\ backslash
Date : 10/17/2017 Aim : Math & Numbers (lesson 4) Multiple declarations It s possible to declare and / or initialize multiple variables in one statement: double x = 31.2, m, p = 43.917; int i, j = 2, k; note: declare vs. initialize The assignment operator Equal Sign = Fundamental arithmetic operations Addition + Subtraction - Multiplication * Division / Modulo % PEMDAS ( ) exponent * / + - Increment & Decrement ++i Increment i, then use it i++ Use i, then increment it --i Decrement i, then use it i -- Use i, then decrement it System.out.println(i++); System.out.println(++i); Compound Operators Compound Operator Example Meaning += x += 3; x = x + 3; -= x -= y - 2; x = x - (y - 2); *= z *= 46; z = z * 46; /= p /= x-z; p = p / (x - z); %= j %= 2 j = j % 2; Integer Division Truncation When dividing two integers, the fractional part is truncated (thrown away): int x = 5; int y = 2; int z = x / y; // the answer is 2
Date : 10/19/2017 Aim : Numbers: Mixed Data Types, Casting, and Constants (lesson 5) Mixed data types: Calculations with double and int Casting: Forcing a variable to a new type Constants: A variable s value CANNOT change Mixed data types Calculations with double and int Java does not like to lose data. It will always want to store a result in the most precise data type involved. If it can t it will give an error: double d = 29.78; int i = d; // error, data loss int p = 20 + 5 * 6.0; //error int j = 29; double k = j; // ok, no data loss Casting Forcing one data type into another double d = 29.78; int ii = (int) d; // forcing d into an int The casting only applies to the number, variable, or parenthetical expression that immediately follows the cast. double d = (double)5 / 4; // 1.25 double e = (double)(5 / 4); //1.0 Remember that when a calculation has numbers that are different data types the result will be the more precise: int m = 4 / 2 * 1.0; // error Constants Variables whose values will not change final double PI = 3.1415927; PI = 72.0; // error The word final is used The variable name is all UPPERCASE Can be created for any data type final String NAME = Mercy ; final int SECTIONS = 8;
Date : 10/25/2017 Aim : Boolean Operators (lesson 8) & Keyboard Input (lesson 7) Boolean Operators: == equal > greater than!= not equal >= greater / equal < less than && and <= less / equal or! not -- applied to boolean variables -- ex: if (!a == b) Truth tables How && ( and ) and ( or ) work with combinations of a and b: a b (a && b) a b (a b) false false false false false false false true false false true true true false false true false true true true true true true true Keyboard Input: 1 - Import the Java io and utility libraries import java.io.*; import java.util.*; 2 - Declare an object to associate with the keyboard - a Scanner object - and give it a name Scanner kb = new Scanner(System.in); 3 - Use the Scanner methods String input = kb.nextline(); Create an object: Scanner kb = new Scanner(System.in); Methods in the Scanner class String equality: nextint(); nextdouble(); next(); nextline(); // kb.nextint(); // kb.nextdouble(); // kb.next(); // kb.nextline(); When comparing two String objects you CANNOT use the == comparator You must use String s equals method: String fruit_1 = apple ; String fruit_2 = cantaloupe ; if (fruit_1.equals(fruit_2)) System.out.println( same ); if (!fruit_1.equals(fruit_2)) System.out.println( different );
Date: 10/30/2017 Aim: Switch & While (lessons 10 & 12) The switch statement is an alternative to the if-then-else decision statement. It is easier to read and write. The while and do-while statements are an alternative to the for loop statement. All 3 are loops but each is used for a different purpose. if versus switch String todo; //------- more code -------- if (todo.equals( + )) { answer = a + b; else if (todo.equals( - )) { answer = a - b; else if (todo.equals( x )) { answer = a * b; else { // division answer = a / b; String todo; //---- more code ----- switch (todo) { case + : answer = a + b; break; case - : answer = a - b; break; case x : answer = a * b; break; default: answer = a / b; } Another if versus switch if (num <= 3) { answer = low ; } else if (num <=6 ) { answer = middle ; } else answer = top ; switch (num) { case 1: case 2: case 3: answer = low ; break; case 4: case 5: case 6: answer = middle ; break; default: answer = top ;
for versus while for (int i=1; i <=10; i++) { System.out.println(i); // versus: Scanner kb = new Scanner (System.in); boolean done = false; String answer; // control expression: i <=10; while (!done) { // control expression:!done System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); while versus do-while while (!done) { // control expression before the loop System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); // versus: do { System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); while (!done); // control expression after Compound Control Expressions int loops = 0; while (!done && loops <= 3 ) { System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); loops++;
Math.random( ); More fun stuff Returns a number between 0 (inclusive) and 1 (exclusive) If you want a random number within a range, multiply the result by the high end of the range Math.random( ) * 5; // returns a number between 0 (inclusive) and 5 (exclusive) return; Exits the program String word = Hello ; if (word.equalsignorecase( hello ))... char letter = word.charat(1); // returns e int offset = word.indexof( e ); // returns 1 int offset = word.tolowercase().indexof( h ); // returns 0 (zero) More java string methods: https://www.javatpoint.com/java-string