Presentation is loading. Please wait.

Presentation is loading. Please wait.

AP Computer Science Mr. Wortzman.

Similar presentations


Presentation on theme: "AP Computer Science Mr. Wortzman."— Presentation transcript:

1 AP Computer Science Mr. Wortzman

2 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? Why did we have to give instructions to LightBot or Alzono in the format we did (as opposed to typing English commands)?

3 Introduction to Java

4 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 Turns out, this makes it ideal for writing programs for the internet as well

5 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 Object-oriented

6 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 A debugger to help track down and fix problems

7 Actually Writing Java Programs
Edit Compile Run Debug

8 Actually Writing Java Programs
Edit Compile Run Debug Java Code Compiler Java Bytecode

9 Actually Writing Java Programs
Edit Compile Run Debug Java VM Machine Code Execute Java Bytecode

10 Actually 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 (IDE) called jGRASP

11 jGRASP Walkthrough

12 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 Classes that define state and behavior shared by a set of objects

13 Your First Java Program
public class FirstProgram { public static void main(String[] args) { System.out.println(“Hello, world!”); }

14 Your First Java Program
Class Method public class FirstProgram { public static void main(String[] args) { System.out.println(“Hello, world!”); } Object Message

15 Writing Java Programs Every Java program consists of one or more classes At least one of these classes must have a “main” method The “main” method defines where the program starts

16 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); } Class Method Statement Statement Statement

17 Java Syntax General form: public class ClassName {
public static void main(String[] args) { statement1; statement2; statement3; ... statementN; }

18 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: print println

19 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: Bookmark this page– it will be your Java bible

20 Java API Walkthrough

21 Java API Scavenger Hunt
Use the Java API to answer the following questions (you may use Bing/Google to help you as well): What does a String represent in Java? How do you get a small portion from a String? How do you find the square root of a number in Java? What is the difference between print and println in PrintStream? What types of things can you generate randomly? What types of things can you read from a Scanner? What is a Float? How can you determine if a character is uppercase?

22 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!”); String is an example of a pre-defined Java class

23 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 Eagles” (all on one line, without the quotes) to the console. Use 3 separate statements.

24 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 */ Comments are ignored when compiling and executing code

25 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 Indenting/aligning things well

26 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) Good: count, numTries, xCoordinate

27 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 e.g. size, numLoops, firstName

28 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 Arguments provide additional information needed by the method

29 Anatomy of a Method Call
System.out.println(“Hello, world!”); Target or Receiver Argument Method Name

30 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 Call: use the method in main (or another method)

31 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 Combine unrelated statements

32 Declaring Static Methods
Syntax: public static void <name>() { <statement>; ... }

33 Declaring Static Methods
Example: public static void printGreeting() { System.out.println(“Hello, world!”); System.out.println(“Welcome to my program.”); }

34 Calling Static Methods
Syntax: <name>(); Example: public static void main(String[] args) { printGreeting(); System.out.println(“This is fun!”); } Output: Hello, world! Welcome to my program. This is fun!

35 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 Exercise 2: Rewrite the above program using static void methods.

36 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 Frost the cookies

37 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

38 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 number of smaller, self-contained subtasks

39 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

40 Procedural Decomposition
This also allows us to eliminate redundancy in our double batch recipe: Making sugar cookies (double batch) Make the batter Bake the cookies (batch #1) Bake the cookies (batch #2) Frost the cookies (batch #1) Frost the cookies (batch #2)

41 Calling Methods You can also call methods from other methods:
public static void startProgram() { printGreeting(); System.out.println(“\nAre you ready to begin?”); }

42 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: Pauses execution at the call site Begins executing the callee from its beginning When execution of the callee is complete, control returns to the caller at the next statement/expression after the call

43 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(); System.out.println(“Are you ready to begin?");

44 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 sequence

45 Escape Sequences Escape sequences are prefixed with a \ (backslash)
\n – newline \" – quotation mark \t – tab \\ - backslash Why do we need this one?

46 Escape Sequences System.out.println("\ta\tb\tc");
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: / \ // \\ /// \\\

47 Static Methods Case Study
Exercise: Write a program to produce these figures. Reduce redundancy as much as possible by using good functional decomposition.

48 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 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. Turn in this program when it is complete.


Download ppt "AP Computer Science Mr. Wortzman."

Similar presentations


Ads by Google