AP COMPUTER SCIENCE
LIGHTBOT/BYOB DEBRIEF
⦿
With your table group, discuss the following:
◼ Did you enjoy these activities? Why or why not?
◼ What did you find most challenging about these activities?
◼ Were there times in LightBot that you had to completely reset your work and try again? If so, why?
◼ Did you ever end up with code in BYOB that did not exactly match the solution? What does that tell you about coding?
A BRIEF HISTORY
⦿
Originally released in 1995 by Sun Microsystems (now a
subsidiary of Oracle)
⦿
Designed to write programs for “embedded devices,”
specifically TVs
◼ As such, Java is designed for small, lightweight programs
KEY CHARACTERISTICS
⦿
“Write-once, run anywhere”
◼ Java programs are compiled to bytecode rather than machine code ◼ The bytecode can be executed by any Java VM on any computer
⦿
Automatic memory management
◼ Java tracks what memory is currently in use and reclaims memory that is no longer needed
◼ Other languages (such as C/C++) require the developer to track this himself
ACTUALLY
WRITING JAVA PROGRAMS
⦿
Writing and running programs requires a number of tools:
◼ An editor to write and edit the code
◼ A compiler to translate the program from Java code to Java bytecode
◼ A virtual machine or runtime to translate the bytecode to machine code, which the computer can execute
ACTUALLY
WRITING JAVA PROGRAMS
ACTUALLY
WRITING JAVA PROGRAMS
Java Code
Compiler
Java
Bytecode
ACTUALLY
WRITING JAVA PROGRAMS
Java VM
Machine
Code
Execute
Edit
CompileRun
DebugACTUALLY
WRITING JAVA PROGRAMS
⦿
We could just use notepad (or any other text editor) and
command-line tools
◼ javac (compiler) and java (vm)
⦿
This is very simple and lightweight, but has a lot of
drawbacks
◼ Very little confirmation we’re doing things right ◼ Introduces multiple potential points of failure
⦿
Instead, we will use an integrated development environment
OBJECT-ORIENTED PROGRAMMING
⦿
OOP is based on four main concepts:
◼ Objects that represent actors in a program
◼ Messages that trigger behavior or request data from objects
◼ Methods that perform some set of actions
YOUR FIRST JAVA PROGRAM
public class FirstProgram {
public static void main(String[] args) {
System.out.println(“Hello, world!”);
YOUR FIRST JAVA PROGRAM
public class FirstProgram {
public static void main(String[] args) {
System.out.println(“Hello, world!”);
}
}
Class
Metho
d
WRITING JAVA PROGRAMS
⦿
Every Java program consists of one or more classes
⦿
At least one of these classes must have a “main” method
JAVA SYNTAX
⦿
Java programs are made up of one or more
classes, each with one or more methods, each of
which consists of one or more statements
◼
Statements are like blocks in BYOB
public class Program {
public static void main(String[] args) {
int i = 5;
System.out.println(“Hello!”);
System.out.println(i + 2);
JAVA SYNTAX
⦿
General form:
public class ClassName {
public static void main(String[] args) {
statement1;
statement2;
statement3;
...
statementN;
OUR FIRST OBJECT
⦿
A
PrintStream
called
System.out
⦿
Short version:
System.out
is used to output text
to the console
⦿
Two primary methods used to print output:
WRITING JAVA PROGRAMS
⦿
Java has many, many predefined classes and objects that
provide common behavior
◼ System.out from our program is one example
⦿
This prevents Java developers from having to constantly
“reinvent the wheel”
⦿
These classes and objects (collectively referred to as the
“Java API”) are documented on the Java website:
◼ http://download.oracle.com/javase/7/docs/api/
JAVA API SCAVENGER HUNT
⦿
Use the Java API to answer the following questions (you may
use Bing/Google to help you as well):
1. What does a String represent in Java?
2. How do you get a small portion from a String?
3. How do you find the square root of a number in Java?
4. What is the difference between print and println in
PrintStream?
5. What types of things can you generate randomly?
6. What types of things can you read from a Scanner? 7. What is a Float?
STRINGS
⦿
A sequence of characters is called a string
◼ Strings are usually, but not exclusively, used for input and output
⦿
Strings in Java are enclosed in double-quotes (“string”)
◼ Identify the string in System.out.println(“Hello, world!”);
OUR FIRST OBJECT
⦿
Exercise 1: Write a Java program to print the following to
the console:
My name is <your name> and I love Java!!
⦿
Exercise 2: Write a Java program to print “
Go Issaquah
DOCUMENTATION
⦿
Documentation refers to elements of code that help a reader
understand what’s going on
◼ Comments are the primary, but not the only, form of documentation
⦿
Two types of comments in Java:
◼ Single-line comments:
// this is a single-line comment
◼ Multi-line (or C-style) comments:
/* this is a
multi-line comment */
DOCUMENTATION
⦿
Use comments frequently to:
◼ Describe the basic, high-level behavior of a chunk of code ◼ Explain anything potentially unclear or tricky
◼ Explain why you chose to do something a certain way if there were multiple options
◼ Etc.
⦿
You should also make your code self-documenting by:
◼ Choosing descriptive, readable names ◼ Using line breaks
IDENTIFIERS
⦿
The names of classes, methods, variables, etc. are referred
to as identifiers
⦿
Identifiers can consist of letters, digits, or underscores
◼ The first character cannot be a digit
⦿
Identifiers should be descriptive, but not unwieldy
◼ Bad: x (non-descriptive), myVariableThatIsUsedToCountSomething (too long)
IDENTIFIERS
⦿
Java has certain conventions for identifiers
⦿
Identifiers are always a single word (no spaces)
⦿
Class names should start with an uppercase letter, and use an
uppercase letter to indicate word breaks
◼ e.g. String, PrintStream, MixedFraction ◼ This is called Pascal casing
⦿
Variables/methods/etc. should start with a lowercase letter,
and be cased similarly
METHODS
⦿
A method is a defined behavior of a particular class
⦿
Passing a message in Java is referred to as calling (or
invoking) a method
⦿
Method calls have the following parts:
◼ The target or receiver of the message is the object whose behavior we want to trigger
◼ The method name of the method we want to call ◼ If necessary, some number of arguments
ANATOMY OF A METHOD CALL
System.out.println(“Hello, world!”);
Target or
Receiver
Method
Name
STATIC METHODS
⦿
A static void method is a simple collection of statements
◼ We’ll learn precisely what those modifiers mean soon ◼ Where have you seen them before?
⦿
Three phases to using a static method:
◼ Design: decide what the method will do; write an algorithm
◼ Define: write the code to give your method a name and describe
what it does
STATIC METHODS
⦿
When should we define a new method?
⦿
Ideally a method should be:
◼
Reusable: methods should consist of code we’ll need more than once
◼Specialized: each method should perform a specific subtask
◼
Modular: each method should be (more or less) self-contained
⦿We should not use methods to:
◼
Give a single statement a new name
DECLARING STATIC METHODS
⦿
Syntax:
public static void <name>() { <statement>;
<statement>; <statement>; ...
DECLARING STATIC METHODS
⦿
Example:
public static void printGreeting() {
System.out.println(“Hello, world!”);
CALLING STATIC METHODS
⦿
Syntax:
<name>();
⦿
Example:
public static void main(String[] args) { printGreeting();
System.out.println(“This is fun!”); }
⦿
Output:
Hello, world!
STATIC METHODS
⦿
Exercise 1: Write a program that prints your name in the
following forms:
◼ FirstName LastName
◼ FirstName MiddleName LastName
◼ LastName, FirstName
◼ LastName, FirstName MiddleName
PROCEDURAL DECOMPOSITION
⦿
Imagine an algorithm for making cookies:
◼Making sugar cookies
Mix the dry ingredients
Cream the butter and sugar Beat in the eggs
Stir the dry ingredients into the wet Set the oven to 400°
Put the cookies in the oven Bake for 10 minutes
Remove the cookies from the oven and allow them to cool Mix the ingredients for the frosting
PROCEDURAL DECOMPOSITION
⦿
What if we were making a double batch?
◼ ...
◼ Set the oven to 400°
◼ Put the first batch of cookies in the oven ◼ Bake for 10 minutes
◼ Remove the cookies from the oven and allow them to cool ◼ Put the second batch of cookies in the oven
◼ Bake for 10 minutes
PROCEDURAL DECOMPOSITION
⦿
This algorithm is unstructured, making it hard to follow
⦿
It’s also redundant in the double batch case
⦿
We can do better!
⦿
Procedural decomposition: breaking a large task down into a
PROCEDURAL DECOMPOSITION
⦿
We can decompose our
recipe into three
subtasks:
◼
Making sugar cookies
Make the batter
Bake the cookies
Frost the cookies
⦿
The first subtask is
defined as:
◼
Make the batter
Mix the dry ingredients
Cream the butter and
sugar
PROCEDURAL DECOMPOSITION
⦿
This also allows us to eliminate redundancy in our double
batch recipe:
◼ Making sugar cookies (double batch)
Make the batter
CALLING METHODS
⦿
You can also call methods from other methods:
public static void startProgram() {
printGreeting();
System.out.println(“\nAre you ready to begin?”);
METHOD CALL CONTROL FLOW
⦿
The point at which a method is called is referred to as the
call site
⦿
The method that is being called is the callee
⦿
The method doing the calling is the caller
⦿
When a method is called, the program:
1. Pauses execution at the call site
2. Begins executing the callee from its beginning
3. When execution of the callee is complete, control returns to
METHOD CALL CONTROL FLOW
⦿
Example:
public static void main(String[] args) {
printGreeting();
startProgram();
}
System.out.println("Hello, world!");
System.out.println("Welcome to my program."); System.out.println("This is fun!");
printGreeting();
ESCAPE SEQUENCES
⦿
Some characters cannot be included in a string
◼ Can you think of any examples? ◼ ", newline
⦿
To include these (and other special characters) we use an
ESCAPE SEQUENCES
⦿
Escape sequences are prefixed with a
\
(backslash)
◼ \n – newline
◼ \" – quotation mark ◼ \t – tab
◼ \\ - backslash
ESCAPE SEQUENCES
⦿ Exercise 1: What output is produced by these statements? (Do NOT use your computer!)
◼ System.out.println("\ta\tb\tc");
◼ System.out.println("\\\\");
◼ System.out.println("'");
◼ System.out.println("\"\"\"");
◼ System.out.println("C:\nin\the downward spiral");
⦿ Exercise 2: Write a Java statement to produce this output:
STATIC METHODS CASE STUDY
⦿
Exercise: Write a program to produce these
PROCEDURAL DECOMPOSITION PRACTICE
⦿
Exercise: Write a program to print out the lyrics to "The Old
Lady Who Swallowed a Fly" (lyrics can be found at
http://www.timmyabell.com/music/lyrics/ol/oldlady.htm
).
◼ Use good procedural decomposition and eliminate as much redundancy from the program as possible.
◼ Also, ensure that main is a concise summary of the program's behavior.