Вы находитесь на странице: 1из 34

What’s in ICS.

H22
1. Algorithms and Data 2. Java
– Useful because commonly
Structures used
– From simple to more – Great example of an object-
complex oriented language
– All very fundamental and • Object-oriented languages
useful encourage code reuse and
– You practice algorithmtic good code design
thinking… => 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 James Gosling
• founded Sun Microsystems • early fame as the author
(early 80s) of “Gosling Emacs” (killed
• “the network is the computer” by GNU)
(a little ahead of its time) • then onto Sun’s “NeWS”
– target workstation market window system (killed by
• missed the boat on PC X)
revolution, retreated to Aspen, • lesson: keeping things
Colorado 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 IBM PowerPC 750


for iMac
Intel Pentium

very basic instructions,


- 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
movl (%edx,%eax),
or simply assembly is %ecx
a human-readable movl 12(%ebp), %eax
notation for the leal 0(,%eax,4), %edx
machine language movl $nodes, %eax
movl (%edx,%eax),
%eax
it’s much easier to fldl (%ecx)
remember: fsubl (%eax)
movl %al, 97 movl 8(%ebp), %eax
than leal 0(,%eax,4), %edx
movl $nodes, %eax
10110000 01100001 movl (%edx,%eax),

Example assembly code fragment


High-Level Programming
Languages
• A high-level
programming language int celsiusTemp = 32;
enables a programmer double fahrenheitTemp;
to specify, in a high
level (close to natural fahrenheitTemp = celsiusTemp *
9.0 / 5.0 + 32;
language), what data a
computer will act upon, if (fahrenheitTemp > 100)
how these data will be System.out.println (“Hot !”);
stored, and what else
actions to take under System.out.println (“OK !”);
various circumstances Example Java Code fragment
• A high-level language is
independent of CPU
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
source machine
compiler
code code
e.g.,
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 Java interpreter


JIT compiler
for Windows for Mac

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 default goto operator synchronized


boolean do if outer this
break double implements package throw
byte else import private throws
byvalue extends inner protected transient
case false instanceof public true
cast final int rest try
catch finally interface return var
char float long short void
class for native static volatile
const future new super while
continue generic null switch

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 class name is an
public class HelloWorld 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
Information provided to the method
created dot
(parameters)
from
PrintStream
class 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”)

Вам также может понравиться