Lec2

advertisement
What’s in ICS.H22
1. Algorithms and Data
Structures
– From simple to more
complex
– All very fundamental and
useful
– You practice algorithmtic
thinking…
2. Java
– Useful because commonly
used
– Great example of an objectoriented language
• Object-oriented languages
encourage code reuse and
good code design
=> Code tends to be more
reliable
• Java is also “strongly
typed” so it’s harder to
make mistakes
– Learning how computers
work: how programs are
compiled and executed.
1+2: Learning algorithms in practice:
Coding and executing them in java
Why Java ?
• Java is an elegant, powerful programming
language
• simpler than other object-oriented languages [e.g., C++]
• Java is the basis of other modern programming languages
[e.g., C#]
• Java is platform independent --- write once run
everywhere
• Java supports multiple platforms (Unix, Windows, Mac),
multiple types of devices (desktops, PDAs, phones,
embedded devices)
• Java has good support
• good multimedia, graphics packages
• good client-server and network support (applet, serverlet)
• good, free Integrated Development Environments (IDE)
Java Programming Language:
Designers
Bill Joy
• BSD Unix guy from Berkeley
• founded Sun Microsystems
(early 80s)
• “the network is the computer”
(a little ahead of its time)
– target workstation market
• missed the boat on PC
revolution, retreated to Aspen,
Colorado
James Gosling
• early fame as the author
of “Gosling Emacs” (killed
by GNU)
• then onto Sun’s “NeWS”
window system (killed by
X)
• lesson: keeping things
proprietary is kiss of death
Java Programming Language: History
• Joy and Gosling joined force, Sun subsidiary,
FirstPerson, Inc. (1992)
• target consumer electronics: PDAs, appliances, phones,
all with cheap infra-red kinds of networks
• need a language that’s small, robust, safe, secure, wired
– started working on C++-– soon gave up hope, decided to start from scratch
• Bad luck (again)
• bad luck: a little ahead of time
–
–
–
–
PDAs died with the demise of Apple Newton
switched to interactive TV (ITV)
the resulting language was called “Oak”
then ITV died too
• good luck (finally)
– the net exploded in 1993
– Oak became Java, rest is history!
Learning Java
• just like learning any new language
– syntax: “new words”
– grammar: how to put them together
– programming: telling a coherent story
– library: use plots already written
• initially needs efforts, but pays off in the
end !
Machine Languages
 The “brain” of a computer is its
Central Processing Unit (CPU)
 A CPU can understand only
very basic instructions,
IBM PowerPC 750
for iMac
Intel Pentium
- e.g., store a given value at a memory location, do
some arithmetic operations, compare two values,
start to execute the instruction at another
location
 The set of instructions of a CPU form the machine
language of the CPU
Machine Languages
 Machine languages, or the instructions understood
by computers, are represented by numbers
 for example, for Intel x86 (which includes
Pentium), the numbers
10110000 01100001
give the instruction: copy number 97 to the
processor register storage named ah.
 Each type of CPU has its own specific machine
language (why?)
 Early programmers wrote programs
using machine languages
- the first programmer is Ada Byron (Lady Lovelace)
Higher-Level Programming
Languages
• Other levels of programming languages
were created to satisfy different objectives,
e.g., make it easier for a human being to
read/write programs:
– assembly languages
– intermediate languages
– high-level languages
Assembly Languages
• Assembly language
or simply assembly is
a human-readable
notation for the
machine language
it’s much easier to
remember:
movl %al, 97
than
10110000 01100001
movl
%ecx
movl
leal
movl
movl
%eax
fldl
fsubl
movl
leal
movl
movl
(%edx,%eax),
12(%ebp), %eax
0(,%eax,4), %edx
$nodes, %eax
(%edx,%eax),
(%ecx)
(%eax)
8(%ebp), %eax
0(,%eax,4), %edx
$nodes, %eax
(%edx,%eax),
Example assembly code fragment
High-Level Programming
Languages
• A high-level
programming language
enables a programmer
to specify, in a high
level (close to natural
language), what data a
computer will act upon,
how these data will be
stored, and what
actions to take under
various circumstances
• A high-level language is
independent of CPU
int celsiusTemp = 32;
double fahrenheitTemp;
fahrenheitTemp = celsiusTemp *
9.0 / 5.0 + 32;
if (fahrenheitTemp > 100)
System.out.println (“Hot !”);
else
System.out.println (“OK !”);
Example Java Code fragment
Programming Languages
• A program written in a high-level language must
be translated into machine language before it
can be executed on a particular type of CPU
• A compiler is a software tool which translates
source code into a specific target language
– typically, that target language is the machine language
for a particular CPU type
e.g.,
source
code
compiler
machine
code
c, c++
gcc
intel x86
HelloWorld.c
HelloWorld.exe
Java Translation
• To be platform independent, Java cannot use the
previous approach
• Java introduces an intermediate language called
bytecode
– Java bytecode is not the machine language for any
traditional CPU, but a virtual machine
– the Java compiler translates Java source code (.java
files) into bytecode (in .class files)
– therefore the Java compiler is not tied to any particular
machine
– Java is thus considered to be architecture-neutral
Java Execution
• To execute a Java program, another piece of
software called an interpreter , translates
between bytecode and the machine language
– an interpreter is specific to a specific machine
language
– the interpreter understands java bytecode, and then
issues instructions in the machine language for which
it is written
– we also say that an interpreter provides a java virtual
machine (JVM)
• Another approach is to have a “just in time” (JIT)
compiler which translates from bytecode to
machine code on the fly, while interpreting it
Java Translation and Execution
Java source code
Java compiler
Java bytecode
Java interpreter
for Windows
Java interpreter
for Mac
JIT compiler
Machine code
Related Topic: Programming
Errors…
A program can have three types of errors
• The compiler will find problems with syntax and
other basic issues (compile-time errors)
– If compile-time errors exist, an executable version of
the program is not created
• A problem can occur during program execution,
such as trying to divide by zero, which causes a
program to terminate abnormally (run-time
errors)
• A program may run, but produce incorrect results
(logical errors)
Java Programming: The Edit/Compile/Run
Loop
• Programming in Java
consists of three tasks
– edit java source code (.java
files)
– compile java source code to
generate bytecode (.class
files)
– execute/run/test bytecode
using an interpreter
An Sample Java Program
//==========================================================
//
// HelloWorld.java
//
// Author: Richard Yang
//
// Class: HelloWorld
//
// --------------------------------------------------------// This program prints a string called "Hello World!”
//
//==========================================================
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
} // end of method main
} // end of class
Comments
• Two types of comments in Java
• single-line comments use
//…
// this comment runs to the end of the line
• multi-lines comments use /*
… */
/* this comment runs to the terminating
symbol, even across line breaks
*/
• Comments are ignored by the compiler:
– used only for human readers (i.e., inline
documentation)
– they should be included to explain the purpose of
the program and describe processing steps
Identifiers
• Identifiers are the words that a programmer
uses in a program
• An identifier can be made up of letters,
digits, the underscore character (_), and
the dollar sign ($)
• An identifier cannot begin with a digit
(why?)
• Java is case sensitive, therefore Total
and total are different identifiers
Three Types of Identifiers
1. Identifiers chosen by ourselves when writing a
program (such as HelloWorld)
2. Identifiers chosen by another programmer, so
we use the identifiers that they chose (e.g.,
System, out, println, main)
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println(“Hello World!”);
}
}
Identifiers: Reserved Words
3. Special identifiers called reserved words that already
have a predefined meaning in the Java language
- a reserved word cannot be used in any other way
abstract
boolean
break
byte
byvalue
case
cast
catch
char
class
const
continue
default
do
double
else
extends
false
final
finally
float
for
future
generic
goto
if
implements
import
inner
instanceof
int
interface
long
native
new
null
operator
outer
package
private
protected
public
rest
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
var
void
volatile
while
Java revered words: they are all lowercase!
Java Program Structure
• In the Java programming language:
– a program is made up of one or more classes
– a class contains one or more methods
• Java application must always contain a method
called main
– a method contains program statements
Java Program Structure:
Class
//
comments about the class
public class HelloWorld
{
class name is an
identifier; convention
we follow: capitalize
each English word
class header
class body starts with a left brace {
and ends with a right brace }
comments can be added almost anywhere
}
Structure of a Java Class
public class Classroom
{
// instance variables
int min_capacity = 0;
int max_capacity = 100;
int chairs = 30;
…
// methods
public int addStudents (int students)
{ … }
public int addChairs (int chairs)
{ … }
…
public static void main (String[] args)
{ … }
}
Java Method and Statements
• Methods
– building blocks of a class
– each method name is an identifier, e.g. “addStudents”
• convention we follow: a method name starts lower case, with
each additional English word capitalized (e.g., main,
doMyJob )
– the main method
• each Java application must have one
• all programs start by executing the main method
– braces are used to start ({) and end (}) a method
• Statements
– every statement must end in a semicolon ;
Classes and Methods
• Methods and classes are language constructs to
help organize a program
– a method “organizes” a sequence of statements
• thus we can use a single method to refer to a bunch of
statements
– a class “organizes” a collection of methods (and data)
• Division of tasks into classes and methods
supports object-oriented programming and
creates good abstraction boundaries between
different tasks and objects
Classes and Methods Provide
Abstraction
• In the jargon of program design, they are
structures which provide abstraction
• The objective of abstraction is to help
programmers to hide (or ignore) the right details
at the right time
• Why abstraction
– a human being can only manage seven (plus or
minus 2) pieces of information at one time
• if we group information into chunks, for example, by
organizing complex software carefully into methods and
classes, we can write more complex software
Methods and Classes
• A method provides an abstraction for a sequence of
statements
– initially, a method helps a programmer to refer to a a sequence
of statements which she may reuse
– more generally, a method defines a service
• a method takes input (parameters), performs some actions, and
(sometime) returns a value
– we invoke a method (call its service) and specify
input/parameters
• A class provides an abstraction for objects with some
common behaviors/services which we can tell them to
perform for us
– the services/behaviors provided by an object are defined by the
methods in the class that defines the object
– we create objects from its class definition: class serves as a
blueprint
Example
• System.out is an object created from the
PrintStream class
• Example: invoking the println method
of the System.out object:
System.out.println ("Whatever you are, be a good one.");
Object
method
created dot
from
PrintStream
class
Information provided to the method
(parameters)
29
Declaring Object Reference Variables
• In the general case, we need to first create
objects
– pre-created objects such as System.out are rare
• To “keep track” of created objects, we need
variables to refer to the created objects
– variables are identifiers
• A variable can be used to refer to different
objects
• To avoid mixing different types of objects, we
should specify the type of objects that a variable
can refer to; thus we need to specify the type of
a variable:
<Type> <variableName>;
Declaring Object Reference Variables
• Example:
String title;
where String is a predefined class in
Java; we also call title an object
reference variable
• No object has been created with the
above declaration of a variable
• The object itself must be created
separately
Explicitly Creating Objects
• We use the new operator to create an
object
title = new String (“Java Software Solutions");
This calls the constructor method of class String,
which is a special method that sets up the object
(every class must have a constructor method)
• Now the variable title refers to an
instance of String object
title
“Java Software Solutions"
Explicitly Creating Objects
title = new String (“Java Software Solutions");
• “new” operator in general:
<varName> = new <className> ([<params>]);
This calls the constructor method of class <className>
which (optionally) takes some parameters <params>
• Now the variable <varName> refers to an object
which is an instance of class <className>
<varName>
Object of class <className>,
constructed using parameters <params>
Use Methods of Objects
title = new String (“Java Software Solutions");
title
“Java Software Solutions"
• Once an object has been instantiated, we can use the dot operator
to invoke its methods, e.g.,
count = title.length();
• This procedure call invokes method “length” of class String,
because “title” is a variable which refers to an object which is an
instance of class String.
• Saying it another way: “title” is a variable of “type” String
• Methods (e.g. method “length” of class String) can return values
(Here the return value is assigned to variable “count”)
Download