Unit 1 - Intro to Javax

Download Report

Transcript Unit 1 - Intro to Javax

http://java.oracle.com
INTRODUCTION TO JAVA
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
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
• Similar to C#
• 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 themselves
• Object-oriented
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/
• Bookmark this page– it will be your lifeline
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
Using Eclipse
• Instead, we’ll use an Integrated Development Environment
(IDE) called Eclipse
• Available for download from http://www.eclipse.org/downloads/
• You want “Eclipse IDE for Java Developers”
• IDEs combine all the tools we need into one centralized,
integrated environment (hence the name)
• Most IDEs (including Eclipse) also provide a bunch of other
useful features
Eclipse Walkthrough
Exercise
• Create Hello World program.
• Outputs “Hello world. My name is <your name>.”
Actually Writing Java Programs
• Writing and running programs requires a number of tools:
• An editor to write and edit the code
• We will use eclipse
• 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
• We will primarily use print statements to track and debug programs.
Actually Writing Java Programs
Edit
Compile
Run
Debug
Actually Writing Java Programs
Edit
Compile
Java
Bytecode
Java VM
Run
Debug
Machine
Code
Actually Writing Java Programs
Edit
Java
Bytecode
Compile
Java VM
Run
Machine
Code
Debug
Execute
Your First Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println();
System.out.println("This program produces");
System.out.println("four lines of output");
}
}
• Its output:
Hello, world!
This program produces
four lines of output
• console: Text box into which
the program's output is printed.
Your First Java program
class: a program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello,
world!");
method:
a named group
System.out.println();
of statements
System.out.println("This program produces");
System.out.println("four lines of output");
}
statement: a command to be executed
}
• Every executable Java program consists of a class,
• that contains a method named main,
• that contains the statements (commands) to be executed.
System.out.println
• A statement that prints a line of output on the console.
• pronounced "print-linn"
• sometimes called a "println statement" for short
• Two ways to use System.out.println :
• System.out.println("text");
Prints the given message as output.
• System.out.println();
Prints a blank line of output.
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
Review
• What is the name of the statement that prints a line of output on the
console?
• System.out.println
• What is Eclipse?
• An IDE that combines all the tools we need into one centralized, integrated
environment
• In the program below,
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println();
System.out.println("This program produces");
System.out.println("four lines of output");
}
}
• What is the name of the program?
• What is the name of a method?
• What is one statement in this program?
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
• Readability of you code is important.
• For clarity and understanding especially on debugging
• You will be graded on the readability of your code.
Bugs
• A bug is anything that goes wrong with a program
• Debugging is the act of going through code and fixing bugs
• In industry, software engineers usually spend more time
debugging code than they did writing it (sometimes orders of
magnitude more)
Bugs
• Eclipse helps you find some bugs:
• Notice the red squiggly and red x
• Hovering over the x tells you what’s wrong
• When you try to compile, you also get an error:
Bugs
• Bugs that can be detected like this are called compile-time
errors
• These are usually relatively simple to find and fix
• Bugs that don’t show up until you try to execute the program
are called run-time errors
• Run-time errors are generally much trickier to deal with
Bugs
• Important takeaway:
ALL PROGRAMS HAVE BUGS, AND YOURS WILL TOO!
• Don’t be discouraged when things don’t work right away
• Keep working at it, and try to see what the code really
does, not what you think it does
• We’ll talk more about debugging and testing later
Names and identifiers
• You must give your program a name.
public class ComputerScience {
• Naming convention: capitalize each word (e.g. MyClassName)
• Your program's file must match exactly (ComputerScience.java)
• includes capitalization (Java is "case-sensitive")
• identifier: A name given to an item in your program.
• must start with a letter or _ or $
• subsequent characters can be any of those or a number
• legal: _myName
TheCure
ANSWER_IS_42
$bling$
• illegal: me+u
49ers
side-swipe
Ph.D's
Identifiers continued
• Identifiers should be descriptive, but not unwieldy
• Bad: x (non-descriptive),
myVariableThatIsUsedToCountSomething (too long)
• Good: count, numTries, xCoordinate
• 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
• This called Camel casing
Keywords
• keyword: An identifier that you cannot use because it already
has a reserved meaning in Java.
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
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(“Welcome to Java!”);
• String is an example of a pre-defined Java class
Escape sequences
• escape sequence: A special sequence of characters used to
represent certain special characters in a string.
\t
\n
\"
\\
tab character
new line character
quotation mark character
backslash character
• Example:
System.out.println("\\hello\nhow\tare
\"you\"?\\\\");
• Output:
\hello
how
are "you"?\\
Review
• What kind of bugs don’t show up until you try to execute the
program?
• Run-time bugs
• What is an identifier?
• A name given to an item in your program
• What kind of casing you should use for classes?
• 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
• What is a keyword?
• An identifier that you cannot use because it already has a
reserved meaning in Java
• In Java, how do you specify a string?
• Strings in Java are enclosed in double-quotes (“string”)
Exercise
• Chapter 1
• Exercises 1-4
Review
• What is the name of the method that all Java applications
must have?
• main
• What is an identifier?
• A name given to an item in your program
• What kind of casing you should use for classes?
• 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
• What is a keyword?
• An identifier that you cannot use because it already has a
reserved meaning in Java
• In Java, what is the escape sequence for a ‘\’ character?
• \\
Static methods
Algorithms
• algorithm: A list of steps for solving a problem.
• Example algorithm: "Bake sugar cookies"
1. Mix the dry ingredients.
2. Cream the butter and sugar.
3. Beat in the eggs.
4. Stir in the dry ingredients.
5. Set the oven temperature.
6. Set the timer.
7. Place the cookies into the oven.
8. Allow the cookies to bake.
9. Spread frosting and sprinkles onto the cookies.
• ...
Problems with algorithms
• lack of structure: Many tiny steps; tough to remember.
• redundancy: Consider making a double batch...
1. Mix the dry ingredients.
2. Cream the butter and sugar.
3. Beat in the eggs.
4. Stir in the dry ingredients.
5. Set the oven temperature.
6. Set the timer.
7. Place the first batch of cookies into the oven.
8. Allow the cookies to bake.
9. Set the timer.
10. Place the second batch of cookies into the oven.
11. Allow the cookies to bake.
12. Mix ingredients for frosting.
• ...
Structured algorithms
• structured algorithm: Split into coherent tasks.
1
•
•
•
•
Make the cookie batter.
Mix the dry ingredients.
Cream the butter and sugar.
Beat in the eggs.
Stir in the dry ingredients.
2
•
•
•
•
Bake the cookies.
Set the oven temperature.
Set the timer.
Place the cookies into the oven.
Allow the cookies to bake.
3 Add frosting and sprinkles.
• Mix the ingredients for the frosting.
• Spread frosting and sprinkles onto the cookies.
...
Removing redundancy
• A well-structured algorithm can describe repeated tasks with
less redundancy.
1 Make the cookie batter.
• Mix the dry ingredients.
• ...
2a Bake the cookies (first batch).
• Set the oven temperature.
• Set the timer.
• ...
2b Bake the cookies (second batch).
3 Decorate the cookies.
• ...
Using static methods
1. Design the algorithm.
• Look at the structure, and which commands are repeated.
• Decide what are the important overall tasks.
2. Declare (write down) the methods.
• Arrange statements into groups and give each group a name.
3. Call (run) the methods.
• The program's main method executes the other methods to
perform the overall task.
A program with redundancy
public class BakeCookies {
public static void main(String[] args) {
System.out.println("Mix the dry ingredients.");
System.out.println("Cream the butter and sugar.");
System.out.println("Beat in the eggs.");
System.out.println("Stir in the dry ingredients.");
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
System.out.println("Mix ingredients for frosting.");
System.out.println("Spread frosting and sprinkles.");
}
}
Static methods
• static method: A named group of statements.
class
• denotes the structure of a program
• eliminates redundancy by code reuse

• procedural decomposition:
dividing a problem into methods



• Writing a static method is like
adding a new command to Java.

• What is a statement?

• statement: a command to be executed


method A
statement
statement
statement
method B
statement
statement
method C
statement
statement
statement
Declaring a method
Gives your method a name so it can be executed
• Syntax:
public static void name() {
statement;
statement;
...
statement;
}
• Example:
public static void printWarning() {
System.out.println("This product causes cancer");
System.out.println("in lab rats and humans.");
}
Design of an algorithm
// This program displays a delicious recipe for baking cookies.
public class BakeCookies2 {
public static void main(String[] args) {
// Step 1: Make the cake batter.
System.out.println("Mix the dry ingredients.");
System.out.println("Cream the butter and sugar.");
System.out.println("Beat in the eggs.");
System.out.println("Stir in the dry ingredients.");
// Step 2a: Bake cookies (first batch).
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the
oven.");
System.out.println("Allow the cookies to bake.");
// Step 2b: Bake cookies (second batch).
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the
oven.");
System.out.println("Allow the cookies to bake.");
}
}
// Step 3: Decorate the cookies.
System.out.println("Mix ingredients for frosting.");
System.out.println("Spread frosting and sprinkles.");
Calling a method
Executes the method's code
• Syntax:
name();
• You can call the same method many times if you like.
• Example:
printWarning();
• Output:
This product causes cancer
in lab rats and humans.
Program with static method
public class Macklemore{
public static void main(String[] args) {
rap();
// Calling (running) the rap method
System.out.println();
rap();
// Calling the rap method again
}
// This method prints the lyrics to Can’t Hold Us.
public static void rap() {
System.out.println("So we put our hands up like the
ceiling can't hold us. ");
System.out.println("Like the ceiling can't hold us");
}
}
Output:
So we put our hands up like the ceiling can't hold us.
Like the ceiling can't hold us
So we put our hands up like the ceiling can't hold us.
Like the ceiling can't hold us
Final cookie program
// This program displays a delicious recipe for baking cookies.
public class BakeCookies3 {
public static void main(String[] args) {
makeBatter();
bake();
// 1st batch
bake();
// 2nd batch
decorate();
}
// Step 1: Make the cake batter.
public static void makeBatter() {
System.out.println("Mix the dry ingredients.");
System.out.println("Cream the butter and sugar.");
System.out.println("Beat in the eggs.");
System.out.println("Stir in the dry ingredients.");
}
// Step 2: Bake a batch of cookies.
public static void bake() {
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
}
// Step 3: Decorate the cookies.
public static void decorate() {
System.out.println("Mix ingredients for frosting.");
System.out.println("Spread frosting and sprinkles.");
}
}
Demo: Methods calling methods
public class MethodsExample {
public static void main(String[] args) {
message1();
message2();
System.out.println("Done with main.");
}
public static void message1() {
System.out.println("This is message1.");
}
public static void message2() {
System.out.println("This is message2.");
message1();
System.out.println("Done with message2.");
}
}
• Output:
This
This
This
Done
Done
is message1.
is message2.
is message1.
with message2.
with main.
Control flow
• When a method is called, the program's execution...
• "jumps" into that method, executing its statements, then
• "jumps" back to the point where the method was called.
public class MethodsExample {
public static void main(String[] args) {
public static void message1() {
message1();
System.out.println("This is message1.");
}
message2();
public static void message2() {
System.out.println("This is message2.");
message1();
System.out.println("Done with main.");
}
System.out.println("Done with message2.");
}
...
}
public static void message1() {
System.out.println("This is message1.");
}
When to use methods
• Place statements into a static method if:
• The statements are related structurally, and/or
• The statements are repeated.
• You should not create static methods for:
• An individual println statement.
• Only blank lines. (Put blank printlns in main.)
• Unrelated or weakly related statements.
(Consider splitting them into two smaller methods.)
Review
• What is a static method?
• A named group of statements
• What is an algorithm?
• A list of steps for solving a problem.
Exercise
• Write a Java program called TwoRockets that generates the following output. Use Static
methods to show structure and eliminate redundancy in your solution. Note that there are
two rocket ships next to each other. What redundancy can you eliminate using static
methods? What redundancy can be eliminated?
/\
/\
/ \
/ \
/
\
+---------+
|
|
|
|
+---------+
|United|
|States |
+---------+
|
|
|
|
+---------+
/\
/ \
/
\
/
\
+---------+
|
|
|
|
+---------+
|United|
|States |
+---------+
|
|
|
|
+---------+
/\
/ \
/
\
Unit 1 Review
1.
2.
3.
4.
5.
6.
Java programs
Identifiers
Method
String
Documentation
Algorithms
Your First Java program
class: a program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
method: a named group
System.out.println();
of statements
System.out.println("This program
produces");
System.out.println("four lines of
output");
}
statement: a command to be executed
}
• Every executable Java program consists of a class,
• that contains a method named main,
• that contains the statements (commands) to be executed.
Identifiers
• The names of classes, methods, variables, etc. are referred to
as identifiers
• Identifiers can consist of letters, digits, underscores (_), or $
• 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
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
Keywords
• keyword: An identifier that you cannot use because it already
has a reserved meaning in Java.
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
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
Anatomy of a Method Call
System.out.println(“Welcome to Java!”);
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
• Readability of you code is important.
• For clarity and understanding especially on debugging
• You will be graded on the readability of your code.
Algorithms
• algorithm: A list of steps for solving a problem.
• Example algorithm: "Bake sugar cookies"
1. Mix the dry ingredients.
2. Cream the butter and sugar.
3. Beat in the eggs.
4. Stir in the dry ingredients.
5. Set the oven temperature.
6. Set the timer.
7. Place the cookies into the oven.
8. Allow the cookies to bake.
9. Spread frosting and sprinkles onto the cookies.
• ...