AP® Computer Science A Lecture 2

Presented by TU RUIXUAN
Copyright © TU RUIXUAN, All Rights Reserved
Tailored for College Board® Advanced Placement® Program
According to Course and Exam Description Effective Fall 2020

Contents (AP CED Equivalent)

  • Unit 1: Primitive Types (including 1.4)
  • Unit 2: Using Objects (excluding 2.6, 2.7, 2.8, 2.9)
  • Unit 3: Boolean Expressions and if Statements (excluding 3.5, 3.6, 3.7)
  • Unit 4: Iteration (excluding 4.3)
  • Unit 5: Writing Classes
  • Unit 9: Inheritance (excluding 9.7)

Topics

T 2.1: More assignment operators

Code Snippet

int a = 1;
a++; // a: 1+1=2
a += 2; // a: 2+2=4
a += (2 + 1) * 3; // a: 4+9=13
++: += 1
--: -= 1
a += b: a = a + b (-=, *=, /=, %=)

T 2.2: if statement

Code Snippet

int a = scanner.nextInt();
if (a > 10) System.out.println("Greater than 10");
else System.out.println("Less than or equal to 10");

\darr How and Conditions \darr

If there is only one line of code after if, else, for, while, etc., we can abbrevate the braces ({ and }).

EXAMPLE

if (a > 10) System.out.println("Greater than 10");

EQUALS TO

if (a > 10) {
    System.out.println("Greater than 10");
}

\darr Conditions \darr

  • ==: equal to
  • !=: not equal to
  • >: greater than
  • >=: greater than or equal to
  • <: less than
  • <=: less than or equal to
  • &&: conditional-AND
  • ||: conditional-OR

\darr Example \darr

if (a == 0 || a == 1) System.out.println("a is 0 or 1");
else System.out.println("a is not 0 or 1");

T 2.3: switch statement

Code Snippet

int a = scanner.nextInt();
switch (a) {
    case 0:
    case 4:
        System.out.println("a=0 or 4");
        break;
    case 1:
        System.out.println("a=1");
        break;
    default:
        System.out.println("a!=0, 1, or 4");
}

Be sure to break; after each case if not intended

T 2.4: for loop (1)

Code Snippet

int a = scanner.nextInt();
for (int i = 0; i < a; i++)
    System.out.println(i);

Format (© Oracle)

for (initialization; termination; increment) {
    statement(s)
}

\darr Sample \darr

Sample Input #1

5

Sample Output #1

0
1
2
3
4

Sample Input #2

0

Sample Output #2

T 2.5: while loop

Rewrite of T 2.3

Code Snippet

int a = scanner.nextInt();
int i = 0;
while (i < a) {
    System.out.println(i);
    i++;
}

Format (© Oracle)

while (expression) {
     statement(s)
}

\darr Sample \darr

Sample Input #1

5

Sample Output #1

0
1
2
3
4

Sample Input #2

0

Sample Output #2

T 2.6: do-while loop

Rewrite of T 2.3 BUT different

Code Snippet

int a = scanner.nextInt();
int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < a);

Format (© Oracle)

do {
     statement(s)
} while (expression);

\darr Sample \darr

Sample Input #1

5

Sample Output #1

0
1
2
3
4

Sample Input #2

0

Sample Output #2 (CHANGED)

0

\darr How \darr

The difference between do-while and while

  • do-while evaluates its expression at the bottom of the loop instead of the top which is used in while.
  • Therefore, the statements within the do block are always executed at least once.

T 2.7: Loop keywords

Code Snippet

for (int i = 0; i < 5; i++) {
    if (i == 1) continue;
    if (i == 3) break;
    System.out.println(i);
}

Output

0
2

\darr Explaination \darr

  • continue: ignore following statements and enter the next loop
  • break: ignore following statements and exit the loop

T 2.8: Class basics

Code #1

public class Employee {
    private String name;
    private int salary = 100;
    public static int total = 0;

    public Employee(String name) { // constructor
        this.name = name;
        total += 100;
    }

    public Employee(String name, int salary) { // overloaded constructor
        this.name = name;
        this.salary = salary;
        total += salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public int getSalary() {
        return salary;
    }
}

\darr Usage \darr

Code Snippet #2

Employee bob = new Employee("Bob");
// System.out.println(bob.salary); // ERROR: private
System.out.println(bob.getSalary()); // 100
System.out.println(Employee.total); // 100
Employee bob2 = bob; // reference, NOT copy
System.out.println(bob2.getSalary()); // 100
Employee jack = new Employee("Jack", 200);
System.out.println(jack.getSalary()); // 200
System.out.println(Employee.total); // 300
bob.setSalary(200);
System.out.println(bob.getSalary()); // 200
Employee.total += 100;
System.out.println(Employee.total); // 400

\darr Note \darr

  • this: a reference variable that refers to the current object of a method or a constructor. The main purpose of using this keyword in Java is to remove the confusion between class attributes and parameters that have same names;
  • static: global, shared;
  • Constructor: a function which has the type and name of a class within it is a constructor of the class
  • instance.object: an accessor
  • Mutator: a setter like setSalary()
  • null: a reference to null may cause error (no referenced object)

\darr null \darr

Employee a; // not assigned
Employee b = null; // the same as above
System.out.println(a.getSalary()); // ERROR: NullPointerException
System.out.println(b.getSalary()); // ERROR: NullPointerException
int c = null;
System.out.println(c); // ERROR: NullPointerException

Do assign a value other than null before using any object

T 2.9: Scope

Code Snippet

int a = 1;
{
    int a = 2;
    System.out.println(a);
}
System.out.println(a);
for (int i = 0; i < 3; i++) ;
// System.out.println(i); // ERROR

Output

2
1

A variable is only effective within the covering pair of braces ({ and }).

\darr Null Statement \darr

  • Statement: a line of executable code (usually ends with ;) is a statement
    • Not a statement: while (true), for(int i = 0; i < 1; i++)
    • Is a statement: int a;, bob.getSalary();
  • Null Statement: a statement that do not do anything
    • a.k.a. ;
    • No action but cost execution time

T 2.10: Super class

Code #1

public abstract class Parent {
    public int p;
    public Parent(int p) {
        this.p = p;
    }
}

public class Child extends Parent {
    public int c;
    public Child(int a, int p) {
        super(p);
        this.c = super.p + a;
    }
}

Code Snippet #2

Parent o1 = new Child(1, 2); // (Parent)child
System.out.println(o1.p); // 2
// System.out.println(o1.c); // ERROR

Child o2 = new Child(1, 2);
System.out.println(o2.p); // 2
System.out.println(o2.c); // 3

// Child o3 = new Parent(1, 2); // ERROR

\darr abstract \darr

  • abstract: abstract classes cannot be instantiated, but they can be subclassed;
  • Instance: variable for objects to store their values;
    • Not an instance: class Employee
    • Is an instance: Employee bob = new Employee(); (bob is an instance of the Employee class)

T 2.11: Interface

Code

public interface IC {
    public int a, b, c;
    public void op1();
    public int op2(int arg1, int arg2);
}

public class C implements IC {
    public int a, b, c;
    public void op1() {
        ...
    }
    public int op2(int arg1, int arg2) {
        int r;
        ...
        return r;
    }
}

\darr Note \darr

  • An interface is a completely "abstract class" that is used to group related methods with empty bodies;
  • To access the interface methods, the interface must be "implemented" by another class with the implements keyword. The body of the interface method is provided by the "implement" class.

T 2.12: Dynamic Binding

Code Snippet (© Barron's)

Student s = null;
Student u = new UnderGrad("Tim Border", new int[] {90, 90, 100}, none);
Student g = new GradStudent("Kevin Cristella", new int[] {85, 70, 90}, "none", 1234);
System.out.print("Enter student status: ");
System.out.println("Grad (G), Undergrad (U), Neither (N)");
String str = IO.readString();
if (str.equals("G"))
    s = g;
else if (str.equals("U"))
    s = u;
else
    s = new Student();
s.computeGrade();

Computer waits until runtime to decide the method to call

Homework

H 2.1: Calculator

  • Input
    • A string contains an expression whose format is {integer}{operator}{integer}, and the operator can be +, -, *, or /;
  • Output
    • The result of evaluating the expression, and if the result is a decimal number, you should also print out the decimal part, but if not, you should print the integer part only;
  • Useful Functions
public class String {
    public int length(); // the length of the string object
    public char charAt(int index); // the character at the specified index (from 0), e.g. str.charAt(0) == 'a'
}

\darr Sample \darr

Sample Input #1

1+2

Sample Output #1

3

Sample Input #2

1/2

Sample Output #2

0.5

H 2.2: RepeatR

  • Input
    • The first line contains only one integer nn;
    • The second line contains only one line of string ss.
  • Output
    • There should be only nn lines of repeated ss.

\darr Sample \darr

Sample Input

3 OK

Sample Output

OK
OK
OK

H 2.3: Student

Write a program WHICH

  • at least contains classes Student, UnderGrad, and HighSch
  • using what we have learned so far.

Thanks for Watching

Presented by TU RUIXUAN
Copyright © TU RUIXUAN, All Rights Reserved

AP® Computer Science A Series