• No results found

INTRODUCTION TO JAVA

N/A
N/A
Protected

Academic year: 2020

Share "INTRODUCTION TO JAVA"

Copied!
48
0
0

Loading.... (view fulltext now)

Full text

(1)

AP COMPUTER SCIENCE

(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?

(3)
(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

(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

(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

(7)

ACTUALLY

WRITING JAVA PROGRAMS

(8)

ACTUALLY

WRITING JAVA PROGRAMS

Java Code

Compiler

Java

Bytecode

(9)

ACTUALLY

WRITING JAVA PROGRAMS

Java VM

Machine

Code

Execute

Edit

Compile

Run

Debug

(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

(11)
(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

(13)

YOUR FIRST JAVA PROGRAM

public class FirstProgram {

public static void main(String[] args) {

System.out.println(“Hello, world!”);

(14)

YOUR FIRST JAVA PROGRAM

public class FirstProgram {

public static void main(String[] args) {

System.out.println(“Hello, world!”);

}

}

Class

Metho

d

(15)

WRITING JAVA PROGRAMS

⦿

Every Java program consists of one or more classes

⦿

At least one of these classes must have a “main” method

(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);

(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:

(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:

◼ http://download.oracle.com/javase/7/docs/api/

(20)
(21)

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?

(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!”);

(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

(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 */

(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

(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)

(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

(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 callIf necessary, some number of arguments

(29)

ANATOMY OF A METHOD CALL

System.out.println(“Hello, world!”);

Target or

Receiver

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

(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

(32)

DECLARING STATIC METHODS

⦿

Syntax:

public static void <name>() { <statement>;

<statement>; <statement>; ...

(33)

DECLARING STATIC METHODS

⦿

Example:

public static void printGreeting() {

System.out.println(“Hello, world!”);

(34)

CALLING STATIC METHODS

⦿

Syntax:

<name>();

⦿

Example:

public static void main(String[] args) { printGreeting();

System.out.println(“This is fun!”); }

⦿

Output:

Hello, world!

(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

(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

(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

◼ Bake for 10 minutes

(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

(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

(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:

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

(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();

(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

(45)

ESCAPE SEQUENCES

⦿

Escape sequences are prefixed with a

\

(backslash)

◼ \n – newline

◼ \" – quotation mark ◼ \t – tab

◼ \\ - backslash

(46)

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:

(47)

STATIC METHODS CASE STUDY

⦿

Exercise: Write a program to produce these

(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

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.

References

Related documents

 ntries ntries xits xits  ( ( Cosmetics Cosmetics  etailing etailing on on um umer er el el ct ct on on cs cs  elecommunications elecommunications

The point at which the resultant of lift forces acts is: A) the hub. B) the center of gravity. D) the center of pressure.. A) airflow velocity increasing downward having been

In addition, he concludes that the exchange rate targeting succeed in minimizing the negative and positive trade shocks, and the countercyclical fiscal policy

Acutely exposed animals require calcium gluconate (IV) and oral magnesium hydroxide or milk to bind fluoride before absorption. In chronic exposure, control is difficult unless

Current standards for diabetes management reflect the need to maintain glucose control within a normal range. However, numerous reports indicate that normalization of blood glu-

There are many augmented reality (AR) applications avail- able that can be used to create educational contents for these mobile devices. This paper surveys the most popular

If index futures is trading above 5099, we can buy index stocks in cash market and simultaneously sell index futures to lock the gains equivalent to the difference between