Unit 1

Object-Oriented Programming

Test prepUnit 1 FRQ Test — what to study

The format. You'll write one Java class by hand, containing several methods. On test day you'll be given the scoring guidelines telling you exactly what each method has to do — so you don't need to guess the problem or memorize an answer. What you need is to write the syntax fluently, without looking it up.

The scoring. The test is worth 15 points — five scored items at 3 points each, and work that's partially correct still earns 1.5. So attempt every part: a method with a correct header and one mistake inside is worth far more than a blank.

The five items are the class header plus four methods — which means the class header alone is worth as much as any method. Write it correctly and you've banked 3 points before you write a single method.

What you need to be able to write

Treat this as a checklist. Practice each one by hand, on paper.

  1. A class header and its braces — every method goes inside them.
  2. A void method with an empty body — just the header and { }.
  3. A non-void method that returns an instance variable — the return type must match that variable's type.
  4. A method with a parameter that returns a calculation — declare the parameter's type in the header, and return the result.
  5. An if-else statement inside a method — including calling your class's own other methods from inside it.
  6. Printing with System.out.println() — including printing the value another method returns.

An example with the same shape

Your test will use different names and different values. Study the shapes here, not this code.

public class Bookshelf {

  // instance variables you'd be told to assume
  int shelfCount;
  String label;

  public void reset() {
  }

  public String getLabel() {
    return label;
  }

  public int addBooks(int more) {
    return shelfCount + more;
  }

  public void checkSpace() {
    if (addBooks(2) > 10) {
      reset();
    }
    else {
      System.out.println(getLabel());
    }
  }
}

Read checkSpace() closely — it's the hardest shape on the list, because it does three things at once: an if-else, a call to a method that needs an argument, and printing what another method returns.

Note the addBooks(2) inside the condition. When you have to call a method that takes a parameter, any valid argument is acceptable — pick a number and move on. Don't lose time deciding which one is "right."

Mistakes that cost points

  • The return type doesn't match what you return — void on a method that returns something, or int on a method returning a String
  • A non-void method with no return statement at all
  • Leaving the parameter's type out of the header — addBooks(more) instead of addBooks(int more)
  • Putting an object name in front when calling a method in the same class — write reset();, not myShelf.reset();
  • Missing semicolons, or braces that don't close
  • System.out.println misspelled or miscapitalized

How to practice

  • Write a whole class like the one above from memory, on paper, then check it line by line.
  • Ask the tutor for practice prompts in this shape — it will write you new ones with different names and values.

Select a topic to expand it.

1.1Java Basics

Syntax is the set of rules for how a programmer must write code for a computer to understand it. We write statements to tell Java what to do.

  • Java is case-sensitiveHELLO and hello are different things.
  • Use camel case to capitalize words inside names: painterEmma, NeighborhoodRunner.
  • Keywords are words with a predefined meaning, like public and class.

Anatomy of a Java file

public class NeighborhoodRunner {
  public static void main(String[] args) {

  }
}
  • The class header is the class keyword plus the name of the class. The class name and the file name must matchNeighborhoodRunner lives in NeighborhoodRunner.java.
  • File names usually start with a capital letter; Java source files end in .java.
  • The main method is where the program starts running. main() is the name Java looks for to know where to begin. The keywords public, static, and void have special meanings covered later.

Two types of classes

Java programs typically consist of two kinds of classes:

  • A tester class — the class that contains the main method, where the program starts running.
  • A class that represents an object — it holds the object's attributes and behaviors, and you can instantiate objects from it.

Two types of errors

What it isDoes the program run?
Syntax errorCode that doesn't follow Java's syntax rulesNo — it won't compile
Logic errorProgram runs but behaves incorrectly or unexpectedlyYes — but it does the wrong thing

A syntax error looks like this — the class name doesn't match the file name:

/NeighborhoodRunner.java:1: error: class Neighborhoodrunner is public,
should be declared in a file named NeighborhoodRunner.java
public class Neighborhoodrunner {
       ^

Testing your code early and often is one of the most effective ways to find and correct logic errors.

1.2Intro to Classes and Objects1.13 Object Creation and Storage (Instantiation)

A class is a programmer-defined blueprint from which objects are created. An object is an instance of a class — a copy of the class with its own unique set of information.

Without the class, you can't create an object.

Attributes and methods

Characteristics of an object are stored in instance variables, often called the attributes of the object. Objects have a has-a relationship with their attributes. The actions an object can perform are its methods.

Painter
AttributesxLocation, yLocation, direction, remainingPaint
MethodsturnLeft(), move(), paint(color), takePaint()

Creating an object

Painter alice = new Painter();

Reading it left to right:

  • Painter — specifies the class, or type of object we want.
  • alice — gives a name for the object we can reference. The name can be whatever you choose; use names that are easy to recognize.
  • new — the keyword that tells Java we want a new object.
  • Painter() — calls the constructor in the Painter class to create the object.

A constructor is a block of code that has the same name as the class and tells the computer how to create a new object.

Creating an object is called instantiating it — to instantiate means to call the constructor to create an object. Each time you instantiate, you create another instance of the class, and you can create as many instances as you need.

1.3While Loops2.7 While Loops

A while loop is a type of iteration statement — a control structure that repeatedly executes a block of code.

while (amy.canMove()) {
  amy.move();
}

The condition of a while loop results in a boolean value (true or false) and determines whether or not to execute the block of code. As long as the condition is true, the loop body runs again.

If the condition is initially false, the loop body is not executed at all.

The loop only ends when its condition becomes false — so after a loop terminates, you know the condition must be false.

1.4Writing Void Methods1.9 Method Signatures3.5 Methods: How to Write Them

The method header

public void square()
{
}
  • public — so the method can be used outside of the class.
  • void — the return type, which specifies the value returned before a method completes its execution and exits.
  • square() — the name of the method, followed by parentheses. The parentheses are either empty (no parameters) or contain the method's parameters.

The method signature consists of the name and the parameter list.

What void means

When the return type is void, the method shouldn't have a return value. It performs its intended task but doesn't give a value back to where it was called.

public class Painter {

  public void move() {
    . . .
  }

  public void takePaint() {
    . . .
  }
}

Return and flow of control

To return means to exit a method and go back to the point in the program that called it, with the requested value or information.

public class NeighborhoodRunner {
  public static void main(String[] args) {

    Painter lisa = new Painter();

    lisa.move();
    lisa.takePaint();

  }
}

Once the last statement in the method has been executed — or a return statement is executed — the flow of control returns to the point immediately following where the method was called. Here, lisa.move() runs the move() method in Painter, and when it finishes, the program continues on to lisa.takePaint().

Calling a method from inside the same class

Since a class is a blueprint for an object, we don't refer to a specific object when calling methods in the current class:

public class Painter {

  public void square() {
    move();
    turnLeft();
  }
}
1.5Writing Methods with Parameters1.9 Method Signatures1.10 Calling Class Methods

Some methods need additional information to do their job. The paint() method needs to know what color to paint with.

A parameter defines the type of value to receive when a method or constructor is called.

public void paint(String color)
NameTypeDescription
colorStringthe color of the paint — can be a color name or a hex value

Calling a method with an argument

alice.paint("green");

An argument is the specific value provided when a method or constructor is called. Here "green" is the argument passed into the color parameter.

Parameter vs. argument: the parameter is in the method's definition (what type of value it expects); the argument is the actual value you supply at the call.

1.6If-Statements, If-Else Statements, NOT Logical Operator2.3 if Statements

An if statement is a type of selection statement — a statement that only executes when a condition is true. A selection statement is also called a conditional statement.

if (amy.canMove()) {
  amy.move();
}

The condition of an if statement results in a boolean value (true or false) and determines whether or not to execute the block of code.

The NOT (!) operator

A logical operator is an operator that returns a boolean value. NOT (!) returns the opposite value of the condition.

!hasPaint()
  • returns true if hasPaint() returns false
  • returns false if hasPaint() returns true

Two-way selection (if-else)

A two-way selection statement specifies a block of code to execute when the condition is true and a block of code to execute when the condition is false.

if (amy.canMove()) {
  amy.move();
}
else {
  amy.turnRight();
}

Can the Painter move? Yes → move forward. No → turn right.

Because the else block runs in exactly the cases the if block doesn't, an if followed by an if on the negated condition can be rewritten as a single if-else.

1.7Intro to Variables and Data Types1.2 Variables and Data Types

A variable is a container that stores a value in memory. A variable can hold only one value at a time.

A data type is the format of the data that can be assigned to a variable.

Data typeHoldsExamples
intwhole numbers7, 6784
booleanone of two valuestrue, false
Stringa sequence of characters"purple"

Declaring a variable

int currentX = thea.getX();

Declaration is giving a name and a data type to a variable. When we write the data type (int) and the name of the variable (currentX), we are declaring it.

The variable then gets the value returned from calling the method — here, whatever thea.getX() returns is stored in currentX.

1.8Printing in Java

Printing is how you get information about an object out of your program so you can see it.

int currentX = thea.getX();
System.out.print(currentX);
StatementWhat it does
System.out.print()prints the value, and the cursor stays on the current line
System.out.println()prints the value, and the cursor moves to the next line

With print, the next thing printed continues on the same line:

> 4 _

With println, the next thing printed starts on a new line:

4
> _