Title: Whats in ICS.H22
1Whats in ICS.H22
- 2. Java
- Useful because commonly used
- Great example of an object-oriented language
- Object-oriented languages encourage code reuse
and good code design - gt Code tends to be more reliable
- Java is also strongly typed so its harder to
make mistakes - Learning how computers work how programs are
compiled and executed.
- 1. Algorithms and Data Structures
- From simple to more complex
- All very fundamental and useful
- You practice algorithmtic thinking
12 Learning algorithms in practice Coding
and executing them in java
2Why 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)
3Java 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 Suns NeWS window system (killed by
X) - lesson keeping things proprietary is kiss of
death
4Java 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 thats 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!
5Learning 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 !
6Machine Languages
- The brain of a computer is its Central
Processing Unit (CPU) - A CPU can understand only 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
Intel Pentium
IBM PowerPC 750 for iMac
7Machine Languages
- Machine languages, or the instructions
understood by computers, are represented by
numbers - for example, for Intel x86 (which includes
Pentium), the numbers 10110000
01100001give 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)
8Higher-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
9Assembly Languages
- movl (edx,eax), ecx
- movl 12(ebp), eax
- leal 0(,eax,4), edx
- movl nodes, eax
- movl (edx,eax), eax
- fldl (ecx)
- fsubl (eax)
- movl 8(ebp), eax
- leal 0(,eax,4), edx
- movl nodes, eax
- movl (edx,eax),
- Assembly language or simply assembly is a
human-readable notation for the machine language - its much easier to remember
- movl al, 97
- than
- 10110000 01100001
Example assembly code fragment
10High-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 gt 100)
System.out.println (Hot !) - else
- System.out.println (OK !)
Example Java Code fragment
11Programming 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
compiler
source code
machine code
e.g.,
c, c
intel x86
gcc
HelloWorld.c
HelloWorld.exe
12Java 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
13Java 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
14Java Translation and Execution
Java source code
Java compiler
Java bytecode
Java interpreter for Windows
JIT compiler
Java interpreter for Mac
Machine code
15Related 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)
16Java 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
17An 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
18Comments
- 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
19Identifiers
- 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
20Three 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!)
21Identifiers 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 catc
h char class const continue
default do double else extends false final finally
float for future generic
goto if implements import inner instanceof int int
erface long native new null
operator outer package private protected public re
st return short static super switch
synchronized this throw throws transient true try
var void volatile while
Java revered words they are all lowercase!
22Java 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
23Java Program Structure Class
// comments about the class
class name is anidentifier conventionwe
follow capitalize each English word
public class HelloWorld
class header
class body starts with a left brace and ends
with a right brace
comments can be added almost anywhere
24Structure 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)
25Java 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
26Classes 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
27Classes 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
28Methods 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
29Example
- System.out is an object created from the
PrintStream class - Example invoking the println method of the
System.out object
30Declaring 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 ltTypegt
ltvariableNamegt
31Declaring 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
32Explicitly 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"
33Explicitly Creating Objects
title new String (Java Software Solutions")
ltvarNamegt new ltclassNamegt (ltparamsgt)
This calls the constructor method of class
ltclassNamegt which (optionally) takes some
parameters ltparamsgt
- Now the variable ltvarNamegt refers to an object
which is an instance of class ltclassNamegt
Object of class ltclassNamegt, constructed using
parameters ltparamsgt
ltvarNamegt
34Use 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)