p p p

chantingrompΚινητά – Ασύρματες Τεχνολογίες

10 Δεκ 2013 (πριν από 3 χρόνια και 7 μήνες)

92 εμφανίσεις

The lectures slides are ada
p
ted mainl
y
from
J
J
a
avaHow to Pro
g
ram
py
J
g
Objects First with Java -A Practical Introduction using BlueJ
and other slides from many different sources.
Today you will learn:
￿
Different types of programming languages and which languages are
most widely used
￿

￿











￿
The history of the UML –industry standard object oriented design
language
Bithlthlbjtttibt
￿
B
as
i
c
t
ec
h
no
l
ogy concep
t
s, suc
h
as c
l
asses, o
bj
ec
t
s, a
tt
r
ib
u
t
es,
behaviors, encapsulation and inheritance
￿
To write sim
p
le Java a
pp
lications
ppp
￿
To use input an output statements
￿
Java’s primitive types
Bit
￿
B
as
i
c memory concep
t
s
￿
To use arithmetic operators
￿



￿








￿
To write relational and equality operators
￿
The
coreofthebook
emphasizesachieving
program
￿
The

core

of

the

book

emphasizes

achieving

program

claritythrough the proven techniques of object-
orientedprogramming
oriented

programming
.
￿
live-code approach—Java features presented in
completeworkingJavaprograms
complete

working

Java

programs
.
￿
Download example programs
￿
wwwdeitelcom/books/jhtp8/
￿
www
.
deitel
.
com/books/jhtp8/
￿www.prenhall.com/deitel
￿
Seethe
BeforeYouBegin
sectionafterthe
Preface
￿
See

the

Before

You

Begin
section

after

the

Preface
http://www.tiobe.com/
index.php/content/
paperinfo
/
tpci
/indexhtml
paperinfo
/
tpci
/index
.
html

￿
Overtheyearsmanyprogrammerslearned
structured
￿
Over

the

years
,
many

programmers

learned
structured

programming(C, Pascal, …
￿
Y’lll
bth
strctredprogramming
d
object
￿
Y
ou
’ll

l
earn
b
o
th
str
u
ct
u
red

programming
an
d

object
-
oriented programming—the key programming
methodologyusedbyprogrammerstodayinthiscourse
methodology

used

by

programmers

today
,
in

this

course
.
￿
You’ll create and work with many software objects.
￿
Their
internalstructureisoftenbuiltusingstructured
￿
Their

internal

structure

is

often

built

using

structured
-
programming techniques.
￿
The
logicofmanipulatingobjects
isoccasionally
￿
The

logic

of

manipulating

objects

is

occasionally

expressed with structured programming.
￿
Javahasbecomethelanguageofchoicefor
￿
Java

has

become

the

language

of

choice

for

implementing Internet(network)-based applications
andsoftware
fordevicesthatcommunicateovera
and

software

for

devices

that

communicate

over

a

network.
￿

billionsofJava
enabledmobile
￿






billions

of

Java
-
enabled

mobile

phones and handheld devices.
￿

￿
















enterprisewideprogramming needs.
￿




￿



















￿














￿geared toward developing large-scale, distributed networking
applicationsandweb
basedapplications
applications

and

web
-
based

applications
.
￿

￿









￿geared toward developing applications for small, memory-
constraineddevicessuchascellphonespagersandPDAs
constrained

devices
,
such

as

cell

phones
,
pagers

and

PDAs
.
￿
Hi
g
h-level lan
g
ua
g
es
￿Single statements accomplish substantial tasks.
Cil
hih
lllihi
￿
C
omp
il
ersconvert
hi
g
h
-
l
eve
l

l
anguage programs
i
nto mac
hi
ne
language.
￿
Allowyoutowriteinstructionsthatlookalmostlikeeveryday
￿
Allow

you

to

write

instructions

that

look

almost

like

everyday

English and contain commonly used mathematical notations.
￿





￿





























Java is b
y
far
g
pgggg;
y
the most widely used.
￿
Compiling
ahigh
levellanguageprograminto
￿
Compiling
a

high
-
level

language

program

into

machine language can take a considerable amount of
computertime
computer

time
.
￿
Interpreterprograms execute high-level language
programsdirectly
althoughslowerthancompiled
programs

directly
,
although

slower

than

compiled

programs run.
￿
Javausesaclevermixtureof
compilation
and
￿
Java

uses

a

clever

mixture

of

compilation
and

interpretationto run programs.
￿
JavaevolvedfromC++whichevolvedfromCwhich
￿
Java

evolved

from

C++
,
which

evolved

from

C
,
which

evolved from BCPL and B.
￿

￿

￿Originally implemented in 1972
￿

￿


































￿Became widely known as the UNIX operating system’s
developmentlanguage
development

language
￿Today, most of the code for general-purpose operating
systemsiswritteninCorC++
systems

is

written

in

C

or

C++
.
￿The main high-level language for embedded electronic
s
y
stems.
y
￿

++
￿

++
￿An extension of C
￿




￿

























￿

object
orientedprogramming
￿






object
-
oriented

programming
.
￿Hybrid language—it’s possible to program in either a
C
likestyleanobject
orientedstyleorboth
C
-
like

style
,
an

object
-
oriented

style

or

both
.
￿
1991
￿
1991

￿Recognizing this, Sun Microsystems funded an internal corporate
research project, which resulted in a C++-based language named
J
J
ava
￿Created by James Gosling.
￿
1993
￿The web exploded in popularity
￿Sun saw the potential of using Java to add dynamic contentto web
pages
pages
.
￿
Java garnered the attention of the business community
b
ecause of the
p
henomenal interest in the web.
p
￿
Java programs consist of pieces called classes.
￿
Classes include methodsthat perform tasks and return
information when the tasks complete.
￿

￿





￿Rich collections of existing classes
￿Also known as the Java APIs (Application Programming
If)
I
nter
f
aces
)
￿
Two aspects to learning the Java “world.”
￿
TheJavalanguageit
-
self
The

Java

language

it
self
￿The classes in the extensive Java class libraries
￿
Download the Java API documentation
j/
j
/dld/
￿
j
ava.sun.com
/
j
avase
/d
own
l
oa
d
s
/
￿Scroll down to the Additional Resourcessection and click
the
Download
buttontotherightof
JavaSE6
the

Download
button

to

the

right

of

Java

SE

6

Documentation.
￿


￿




















￿Good Programming Practices—help you write
programsthatareclearermoreunderstandablemore
programs

that

are

clearer
,
more

understandable
,
more

maintainable and easier to test and debug—i.e., remove
p
ro
g
rammin
g
errors.
pgg
￿Common Programming Errors—discuss problems to
watch out for and avoid.
￿


￿













￿


￿























￿Error-Prevention Tips—techniques for removing bugs
fromyourprograms
from

your

programs

￿Look-and-Feel Observations—techniques to help you
desi
g
n the “look” and “feel” of
y
our a
pp
lications’ user
gypp
interfaces
￿
Fortran
(FORmulaTRANslator)
￿
Fortran
(FORmula

TRANslator)

￿Developed by IBM Corporation in the mid-1950s
￿
Usedforscientificandengineeringapplicationsthatrequire
￿
Used

for

scientific

and

engineering

applications

that

require

complex mathematical computations.
￿Still widel
y
used in en
g
ineerin
g
a
pp
lications.
yggpp
￿
COBOL (COmmon Business Oriented Language)
￿Develo
p
ed in the late 1950s b
y
com
p
uter manufacturers, the
pyp
U.S. government and industrial computer users
￿Used for commercial applications that require precise and
ffiiiliflfd
e
ffi
c
i
ent man
i
pu
l
at
i
on o
f

l
arge amounts o
f

d
ata.
￿Much business software is still programmed in COBOL.
￿
Researchinthe1960sresultedintheevolutionof
￿
Research

in

the

1960s

resulted

in

the

evolution

of

structured programming
￿

￿






























￿
Pascal
￿Developed by Professor Niklaus Wirth in 1971
￿Designed for teaching structured programming in academic
environments.
￿
Ada
programming
￿
Ada
programming

￿Developed under the sponsorship of the U.S. Department of
Defense(DOD)duringthe1970sandearly1980s
Defense

(DOD)

during

the

1970s

and

early

1980s
.
￿The DOD wanted a single language to fill most of its needs.
￿
N
amed after Lad
y
Ada Lovelace
,
dau
g
hter of
p
oet Lord B
y
ron.
y,gpy
￿She’s credited with writing the world’s first computer program in
the early 1800s.
S
liki
llifh
￿
S
upports mu
l
t
i
tas
ki
ng

a
ll
ows programmers to spec
if
y t
h
at
many activities in a program are to occur in parallel.
￿
Javathroughatechniquecalled
multithreading
alsoenables
Java
,
through

a

technique

called

multithreading
,
also

enables

programmers to write programs with parallel activities.
￿
BASIC
(Beginner

sAll
-
PurposeSymbolicInstruction
￿












￿Developed in the mid-1960s at Dartmouth College as a means of
writingsimpleprograms
writing

simple

programs
.
￿Used to familiarize novices with programming techniques.
￿
Microsoft’s Visual Basic
Itddithl1990tilifthdltf
￿
I
n
t
ro
d
uce
d

i
n
th
e ear
l
y
1990
s
t
o s
i
mp
lif
y
th
e
d
eve
l
opmen
t
o
f

Microsoft Windows applications.
￿
Microsoft’s latest development tools
￿Corporatewide strategy for integrating the Internet and the web into
computer applications.
￿Implemented in Microsoft’s .NET platform
ThiilVilBi(bdh
￿
Th
ree pr
i
mary programm
i
ng
l
anguages:
Vi
sua
l

B
as
i
c
(b
ase
d
on t
h
e
original BASIC), Visual C++(based on C++) and C#(based on C++
and Java, and developed expressly for the .NET platform).
￿

￿











￿
Javaprogramsnormallygothroughfivephases
￿
Java

programs

normally

go

through

five

phases
￿edit
il
￿comp
il
e
￿load
￿verify
￿execute
￿
WediscussthesephasesinthecontextoftheJavaSE
￿
We

discuss

these

phases

in

the

context

of

the

Java

SE

Development Kit 6 (JDK6) from Sun Microsystems, Inc.
￿





￿




















java.sun.com/javase/downloads/.
￿
CarefullyfollowtheinstallationinstructionsfortheJDK
￿
Carefully

follow

the

installation

instructions

for

the

JDK

provided in the Before You Beginsection of this book to
ensure that
y
ou set u
p

y
our com
p
uter
p
ro
p
erl
y
to com
p
ile
ypypppyp
and execute Java programs.
￿
Sun’s New to Java Center at:
￿java.sun.com/new2java/
￿
Phase1
consistsofeditingafilewithan
editor
￿
Phase

1
consists

of

editing

a

file

with

an

editor

program(normally known simply as an editor).
￿
TypeaJavaprogram(
sourcecode
)usingtheeditor
￿
Type

a

Java

program

(
source

code
)

using

the

editor
￿Make any necessary corrections
￿
Savetheprogram
Save

the

program
￿A file name ending with the extensionindicates that the file
contains Java source code.
￿Linux editors: viand emacs.
￿Windows editors: Notepad, EditPlus
(wwweditpluscom
)TextPad(
wwwtextpadcom
)
(www
.
editplus
.
com
)
,
TextPad

(
www
.
textpad
.
com
)

and jEdit (www.jedit.org).
￿
Integrated development environments (IDEs)
Pidlhhf
dl
￿
P
rov
id
e too
l
s t
h
at support t
h
e so
f
tware-
d
eve
l
opment process,
including editors for writing and editing programs and
debu
gg
ers for locatin
g
lo
g
ic errors

errors that cause
ggg
g
programs to execute incorrectly.
￿
Popular IDEs
Eli(
li
)
Bi
l
f
J
dl
￿
E
c
li
pse
(
www.ec
li
pse.org
)
B
as
i
ctoo
l
f
o
r
J
ava
d
eve
l
opment
￿BlueJ(www.blueJ.org) ToteachObjectOrientation
￿NetBeans
(
www.netbeans.or
g
)
fo
r
moreadvance
d
p
ro
g
rams
(
g
)
pg
￿BorlandTogether(UML modelingtool) UML modelingtool
JBild
(
d
)
th
bt
tl
bf
￿
JB
u
ild
e
r
(
www.co
d
egear.com
)
was
th
e
b
es
t
t
oo
l
b
e
f
ore…
￿IntelliJIDEA
(www.jetbrains.com
)
￿
JCreator
(
www.jcreator.com
)
JCreator
(
www.jcreator.com
)
jGRASP(www.jgrasp.org
)
￿……
￿
Phase2
￿
Phase

2
￿Use the command 
(the Java compiler) to compile
aprogramForexampletocompileaprogramcalled
a

program
.
For

example
,
to

compile

a

program

called

Welcome.java, you’d type
javac
Welcomejava
javac
Welcome
.
java
￿If the program compiles, the compiler produces a .class
filecalled
Welcomeclass
thatcontainsthe
file

called

Welcome
.
class
that

contains

the

compiled version of the program.
￿
JavacompilertranslatesJavasourcecodeinto
bytecodes
￿
Java

compiler

translates

Java

source

code

into

bytecodes
that represent the tasks to execute.
￿
B
y
tecodes are executed b
y
the Java Virtual Machine
yy
(JVM)—a part of the JDK and the foundation of the Java
platform.
Vitlhi
(
VM
)
ftlititht
￿
Vi
r
t
ua
l
mac
hi
ne
(
VM
)

a so
ft
ware app
li
ca
ti
on
th
a
t

simulates a computer
￿
Hidestheunderlyingoperatingsystemandhardwarefromthe
Hides

the

underlying

operating

system

and

hardware

from

the

programs that interact with it.
￿
If the same VM is implemented on many computer
ltflitithtittbdll
pl
a
tf
orms, app
li
ca
ti
ons
th
a
t

it
execu
t
es can
b
e use
d
on a
ll

those platforms.
￿

￿







￿They do not depend on a particular hardware platform.
￿


￿





￿The same bytecodes can execute on any platform containing a
JVMthatunderstandstheversionofJavainwhichthe
JVM

that

understands

the

version

of

Java

in

which

the

bytecodes were compiled.
￿
The JVM is invoked b
y
the



command. For
y

⁴@視⁡ﱩョ⁣ﱥ
Welcome,
y
ou’d t
yp
e the comman
d
yyp
java Welcome
￿
Phase3
￿
Phase

3
￿The JVM places the program in memory to execute it
￿


￿











.
￿Class loadertakes the .classfiles containing the
program

s
bytecodes
andtransfersthemtoprimary
programs

bytecodes
and

transfers

them

to

primary

memory.
￿
Alsoloadsanyofthe
.class
filesprovidedbyJavathat
Also

loads

any

of

the

.class
files

provided

by

Java

that

your program uses.
￿The .classfiles can be loaded from a disk on
y
our
y
system or over a network.
￿
Phase4
￿
Phase

4
￿As the classes are loaded, the bytecodeverifierexamines
their
bytecodes
their

bytecodes
￿Ensures that they are valid and do not violate Java’s
securityrestrictions
security

restrictions
.
￿Java enforces strong security to make sure that Java
p
ro
g
rams arrivin
g
over the network do not dama
g
e
y
our
pgggy
files or your system (as computer viruses and worms
might).
￿
Phase 5
￿
TheJVMexecutestheprogram

sbytecodes
￿












￿JVM typically uses a combination of interpretation and just-in-time
(JIT) compilation.
Althbtdthittdhif
ht
￿
A
na
l
yzes
th
e
b
y
t
eco
d
es as
th
ey are
i
n
t
erpre
t
e
d
, searc
hi
ng
f
or
h
o
t

spots—parts of the bytecodes that execute frequently.
￿A just-in-time (JIT)compiler(the Java HotSpot compiler) translates
hbdihdli’hil
t
h
e
b
yteco
d
es
i
nto t
h
e un
d
er
l
y
i
ng computer

s mac
hi
ne
l
anguage.
￿When the JVM encounters these compiled parts again, the faster
machine-language code executes.
￿Java programs actually go through 2compilation phases
￿One in which source code is translated into bytecodes (for
portabilityacrosscomputerplatforms)
portability

across

computer

platforms)

￿A second in which, during execution, the bytecodes are translated
into machine language for the actual computer on which the
programexecutes
program

executes
.
￿


JavaAPIdocumentation
￿










Java

API

documentation
￿java.sun.com/javase/6/docs/api/index.html
￿
Downloadthisdocumentationtoyourowncomputer
￿
Download

this

documentation

to

your

own

computer
￿java.sun.com/javase/downloads/
￿
AdditionaltechnicaldetailsonmanyaspectsofJava
￿
Additional

technical

details

on

many

aspects

of

Java

development
￿
java.sun.com/reference/docs/index.html
java.sun.com/reference/docs/index.html
￿
CheckingyoursetupReadthe
BeforeYouBegin
￿
Checking

your

setup
.
Read

the

Before

You

Begin

section of the book to confirm that you’ve set up Java
properlyonyourcomputerandthatyou

vecopiedthe
properly

on

your

computer

and

that

youve

copied

the

book’s examples to your hard drive.
￿
UnifiedModelingLanguage(UML)
￿
Unified

Modeling

Language

(UML)
￿A graphical language(notation)that allows people who
desi
g
n software s
y
stems to use an industr
y
-standard notation to
gyy
represent them.
￿
Cha
p
ters12–13
p
resent an ob
j
ect-oriented desi
g
n
p
p
j
g
(OOD)and implementation of the software for a
simple automated teller machine (ATM).
￿
Objects
￿
Objects
￿Reusable software components that model real world
items
items
.
￿Humans think in terms of objects. People, animals,
plantscarsetc
plants
,
cars
,
etc
.
￿Have attributes(e.g., size, shape, color and weight)
￿



￿






































￿



￿






￿Models software in terms similar to those that people use to
describereal
-
worldobjects
describe

real
world

objects
.
￿Classrelationships
￿Inheritancerelationshi
p
s
p
￿Models communication between objects (via messages).
￿Encapsulatesattributes and operations(behaviors) into objects.
￿Information hiding
￿Objects may know how to communicate with one another across
well
defined
interfaces
butnormallytheyarenotallowedtoknow
well
-
defined

interfaces
,
but

normally

they

are

not

allowed

to

know

how other objects are implemented.
￿
Object oriented languages
￿



￿

















￿Allows you to implement an object-oriented design as a
kit
wor
ki
ng sys
t
em.
￿Java is object oriented.
￿
Focus on creatin
g
classes.
g
￿Each contains fields and the set of methods that manipulate
the fields and provide services to clients(i.e., other classes
thatusetheclass)
that

use

the

class)
.
￿Programmers use existing classes as the building blocks for
constructing new classes.
￿

￿


















￿
Associations—relationships between classes.
￿
Packa
g
in
g
software as classes facilitates reuse.
gg
￿
Object
orientedanalysisanddesign(OOAD)
￿
Object
-
oriented

analysis

and

design

(OOAD)

￿Analyzingyour project’s requirements(i.e., determining what
thesystemissupposedtodo
)anddevelopinga
design
that
the

system

is

supposed

to

do
)

and

developing

a

design
that

satisfies them (i.e., deciding how the system should do it).
￿
Unified Modelin
g
Lan
g
ua
g
e
(
UML
)

A sin
g
le
ggg()
g
graphical language for communicating the results of
an
y
OOAD
p
rocess has come into wide use.
yp
￿
The UML is the most widely used graphical
re
p
resentation scheme for modelin
g
ob
j
ect-oriented
pgj
systems.
￿
UsetoolsfromtheJDKtocompileandrunprograms
￿
Use

tools

from

the

JDK

to

compile

and

run

programs
.
￿
Videos at www.deitel.com/books/jhtp8/
HltttdithElid
NtB
ittd
￿
H
e
l
p you ge
t
s
t
ar
t
e
d
w
ith

E
c
li
pse an
d

N
e
tB
eans
i
n
t
egra
t
e
d

development environments.
￿
Videosat
￿
Videos

at
http://eclipsetutorial.sourceforge.net/index.html
￿
HelpyougetstartedwithEclipse
Help

you

get

started

with

Eclipse

￿
Java
application
￿
Java

application
￿A computer program that executes when you use the java
command
tolaunchtheJavaVirtualMachine(JVM)
command
to

launch

the

Java

Virtual

Machine

(JVM)
.
￿
Sample program in Fig. 2.1 displays a line of text.
￿
Comments
￿
Comments
// Fig. 2.1: Welcome1.java
￿indicates that the line is a comment.
￿Used to document programsand improve their readability.
￿Compiler ignores comments.
hbiih
//
i
d
li
i
￿A comment t
h
at
b
eg
i
ns w
i
t
h

//
i
s an en
d
-of-
li
necomment

i
t
terminates at the end of the line on which it appears.
￿
Traditionalcomment
canbespreadoverseverallinesasin
￿
Traditional

comment
,
can

be

spread

over

several

lines

as

in
/* This is a traditional comment. It
can be split over multiple lines */
￿This type of comment begins with /*and ends with */.
￿All text between the delimiters is ignored by the compiler.
￿
Javadoccomments
￿
Javadoc

comments
￿Delimited by څڅand څ.
￿

￿





















￿Enable
y
ou to embed
p
ro
g
ram documentation directl
y
in
y
our
ypgyy
programs.
￿The ڿutility program(AppendixM) reads Javadoc
dh’
comments an
d
uses t
h
em to prepare your program

s
documentation in HTML format.
￿

￿










￿Make programs easier to read.
￿



￿






















￿White s
p
ace is i
g
nored b
y
the com
p
iler.
pgyp
￿
Classdeclaration
￿
Class

declaration
public classWelcome1
￿
EveryJavaprogramconsistsofatleastoneclassthatyou
Every

Java

program

consists

of

at

least

one

class

that

you

define.
￿ێێke
y
wor
d
introduces a class declaration and is
y
immediately followed by the class name.
￿Keywords(AppendixC) are reserved for use by Java and are
llldithlllltt
a
l
ways spe
ll
e
d
w
ith
a
ll

l
owercase
l
e
tt
ers.
￿
Classnames
￿
Class

names
￿By convention, begin with a capital letter and capitalize the
firstletterofeachwordtheyinclude(eg
first

letter

of

each

word

they

include

(e
.
g
.,
SampleClassName).
￿A class name is an identifier—a series of characters consisting
of letters, digits, underscores (ں) and dollar signs ($) that does
not begin with a digit and does not contain spaces.
Ji
iti
dlltt
￿
J
ava
i
s case sens
iti
ve

uppercase an
d

l
owercase
l
e
tt
ers are
distinct—so a1and A1are different (but both valid)
identifiers.
￿

￿

￿A left brace, , begins the bodyof every class declaration.
￿
Acorresponding
rightbrace
,

,mustendeachclass
A

corresponding

right

brace
,


,

ﵵ

e



c

說︮d
￿Code between braces should be indented.
￿This indentation is one of the spacing conventions mentioned
earlier.
￿
Declaringthe
main
Method
￿
Declaring

the

main
Method
public static void main( String[] args )
￿Startin
g

p
oint of ever
y
Java a
pp
lication.
gpypp
￿Parenthesesafter the identifier mainindicate that it’s a
program building block called a method.
￿

￿


















￿mainmust be defined as shown; otherwise, the JVM will not
execute the application.
￿Methods perform tasks and can return information when they
complete their tasks.
￿

ڿ
葉i拾ﵥ、ﱬ﹯na
￿


ڿ
葉i



拾

ﵥ、

ﱬ

﹯n



a

葉說︮i
￿

￿









￿Enclosed in left and right braces.
￿

￿

System.out.println("Welcome to Java Programming!");
￿Instructs the computer to perform an action
￿Print the stringof characters contained between the double
quotation marks.
￿A strin
g
is sometimes called a character strin
g
or a strin
g

g
g
g
literal.
￿White-space characters in strings are not ignored by the
compiler
compiler
.
￿Strings cannot span multiple lines of code.
￿
Systemout
object
￿
System
.
out
object
￿Standard output object.
￿


￿



















￿
Syste
m
.out.p
rin
t
lnm
et
h
od

Syste.out.pt
etod
￿Displays (or prints) a line of text in the command window.
￿The strin
g
in the
p
arentheses the ar
g
umentto the method.
gp
g
￿Positions the output cursor at the beginning of the next line in
the command window.
￿
Most statements end with a semicolon.
￿
CompilingandExecutingYourFirstJavaApplication
￿
Compiling

and

Executing

Your

First

Java

Application
￿Open a command window and change to the directory where the
p
ro
g
ram is stored.
pg
￿Many operating systems use the command cdto change directories.
￿To compile the program, type
j
l1j
j
avacWe
l
come
1
.
j
ava
￿If the program contains no syntax errors, preceding command creates
a.classfile
(
known as the class file
)
containin
g
the
p
latform-
(
)gp
independent Java bytecodesthat represent the application.
￿When we use the javacommand to execute the application on a
givenplatformthese
bytecodes
willbetranslatedbytheJVMinto
given

platform
,
these

bytecodes
will

be

translated

by

the

JVM

into

instructions that are understood by the underlying operating system.
￿
To execute the program, type java Welcome1.
hhhihldh
l
filfl
￿
Launc
h
es t
h
e JVM, w
hi
c
h

l
oa
d
s t
h
e .c
l
ass
fil
e
f
or c
l
ass
Welcome1.
￿

class
file
nameextensionisomittedfromthe
￿





.
class
file
-
name

extension

is

omitted

from

the

preceding command; otherwise, the JVM will not execute the
p
ro
g
ram.
pg
￿
The JVM calls method mainto execute the program.
￿
Class
Welcome2
showninFig
23usestwo
￿
Class

Welcome2
,
shown

in

Fig
.
2
.
3
,
uses

two

statements to produce the same output as that shown in
Fi
g
.2.1.
g
￿
New and key features in each code listing are
highlighted.
￿
System.out’s method printdisplays a string.
￿
Unlike println, printdoes not position the output
cursor at the be
g
innin
g
of the next line in the command
window.
Ththtthdilill
￿
Th
e nex
t
c
h
arac
t
er
th
e program
di
sp
l
ays w
ill
appear
immediately after the last character that printdisplays.
￿


Systemout

s
print
and
￿







System
.
out
s
print
and

printlnmethods when to position the output cursor at
the beginning of the next line in the command window.
￿
Newline characters are white-space characters.
￿
The backslash(\n) is called an escape character.
di“ilh”
￿In
di
cates a

spec
i
a
l
c
h
aracter


￿
Backslash is combined with the next character to form an
escapesequence
escape

sequence
.
￿
The escape sequence \nrepresents the newline character.
￿
Com
p
lete list of esca
p
e se
q
uences
ppq
java.sun.com/docs/books/jls/third_edition/html/
lexical.html#3.10.6.
￿

ێ
method
￿

ێ
method

￿fmeans “formatted”
￿displays formatted data
￿
Multiplemethodargumentsareplacedina
comma
-
separatedlist
￿
Multiple

method

arguments

are

placed

in

a

comma
-
separated

list
.
￿
Java allows large statements to be split over many lines.
￿Cannot split a statement in the middle of an identifier or string.
Mthd
printf
’fitti
ftti
￿
M
e
th
o
d

printf

s
fi
rs
t
argumen
t

i
s a
f
orma
t
s
t
r
i
ng
￿May consist of fixed textand format specifiers.
￿Fixed text is output as it would be by printor println.
Ehftifiilhldfldifitht
￿
E
ac
h

f
orma
t
spec
ifi
er
i
s a p
l
ace
h
o
ld
er
f
or a va
l
ue an
d
spec
ifi
es
th
e
t
ype
of data to output.
￿
Format specifiers begin with a percent sign (%) and are followed
bhtthttthdtt
b
y a c
h
arac
t
er
th
a
t
represen
t
s
th
e
d
a
t
a
t
ype.
￿
Format specifier ڀێis a placeholder for a string.
￿
Integers
￿
Integers
￿Whole numbers, like –22, 7, 0 and 1024)
￿
Programsremembernumbersandotherdatainthe
￿
Programs

remember

numbers

and

other

data

in

the

computer’s memory and access that data through
programelementscalled
variables
program

elements

called

variables
.
￿
The program of Fig.2.7 demonstrates these concepts.
￿
import
declaration
￿
import
declaration
￿Helps the compiler locate a class that is used in this
program
program
.
￿Rich set of predefined classes that you can reuse rather
than

reinventingthewheel

than

reinventing

the

wheel
.
￿Classes are grouped into packages—named groups of
relatedclasses

andarecollectivelyreferredtoasthe
related

classes
and

are

collectively

referred

to

as

the

Java class library, or the Java Application Programming
Interface
(
JavaAPI
).
Interface

(
Java

API
).

￿You use importdeclarations to identify the
p
redefined classes used in a Java
p
ro
g
ram.
ppg
￿
Variabledeclarationstatement
￿
Variable

declaration

statement
Scanner input = newScanner( System.in );
￿Specifies the name (input) and type (Scanner) of a variable that
idihi
i
s use
d

i
n t
hi
s program.
￿
Variable
￿
Alocationinthecomputer

smemorywhereavaluecanbestoredfor
A

location

in

the

computers

memory

where

a

value

can

be

stored

for

use later in a program.
￿Must be declared with a nameand a typebefore they can be used.
￿



￿

























￿The name can be any valid identifier.
￿A variable’s type specifies what kind of information is stored at that
location in memory.
￿
Scanner
￿
Scanner
￿Enables a program to read data for use in a program.
￿Data can come from many sources, such as the user at the keyboard or a
file on disk.
￿Before using a Scanner, you must create it and specify the source of
the data.
￿
The e
q
uals si
g
n
(
=
)
in a declaration indicates that the variable
qg(
)
should be initialized(i.e., prepared for use in the program) with
the result of the expression to the right of the equals sign.
￿

new
keywordcreatesanobject.
￿


new
keyword

creates

an

object.
￿
Standard input object, System.in, enables applications to read
bytes of information typed by the user.
￿
Scanner
objecttranslatesthesebytesintotypesthatcanbe
￿
Scanner
object

translates

these

bytes

into

types

that

can

be

used in a program.
￿

￿






intnumber1; // first number to add
intnumber2; // second number to add
intsum; // sum of number1 and number2
declare that variables number1, number2and sumhold
dataoftype








￿They can hold integer.
￿
Rangeofvaluesforan
int
is

2,147,483,648to
+
2,147,483,647.
Range

of

values

for

an

int
is

2,147,483,648

to

2,147,483,647.

￿Actual intvalues may not contain commas.
￿
Several variables of the same type may be declared in one
declaration with the variable names separated by commas.
￿
Prompt
￿
Prompt
￿Output statement that directs the user to take a specific action.
￿
System
isaclass
￿
System
is

a

class
.
￿Part of package java.lang.
￿
Class
System
isnotimportedwithan
import
declarationat
￿
Class

System
is

not

imported

with

an

import
declaration

at

the beginning of the program.
￿
Scannermethod nextInt
b1i()
//dfibf
num
b
er
1
=
i
nput.nextInt
()
;

//
rea
d fi
rst

num
b
er
f
rom

user
￿Obtains an integer from the user at the keyboard.
￿Program waits for the user to type the number and press the
Enter key to submit the number to the program.
￿

nextInt
isplacedin
￿














nextInt
is

placed

in

variable number1by using the assignment operator, ژ.
￿“number1
g
ets the value of in
p
ut.nextInt
()

g
p()
￿Operator =is called a binary operator—it has two operands.
￿Everything to the right of the assignment operator, =, is always
ltdbfthitifd
eva
l
ua
t
e
d

b
e
f
ore
th
e ass
i
gnmen
t

i
s per
f
orme
d
.
￿

￿

sum = number1 + number2; // add numbers
￿A
ss
i
g
nm
e
nt
s
tat
e
m
e
nt that
c
al
cu
lat
es
th
e

su
m
o
f th
e

v
aria
b
l
es

ssgeseeccuesesuoevbes
number1and number2then assigns the result to variable sum
by using the assignment operator, =.
b
b
￿“sumgets the value of num
b
er1+num
b
er2.”
￿In general, calculations are performed in assignment statements.
Ptiftttthttilltilld
￿
P
or
ti
ons o
f
s
t
a
t
emen
t
s
th
a
t
con
t
a
i
n ca
l
cu
l
a
ti
ons are ca
ll
e
d

expressions.
￿
Anexpressionisanyportionofastatementthathasavalue
An

expression

is

any

portion

of

a

statement

that

has

a

value

associated with it.
￿
Integerformattedoutput
￿
Integer

formatted

output
System.out.printf( "Sum is %d\n", sum );
￿
Formatspecifier
ڀڿ
isaplaceholderforan
int
value
Format

specifier

ڀڿ
is

a

placeholder

for

an

int
value
￿The letter dstands for “decimal integer.”
￿
Variables
￿Every variable has a name, a type, a size(in bytes) and a value.
￿When a new value is placed into a variable, the new value
replacesthepreviousvalue(ifany)
Thepreviousvalueislost
replaces

the

previous

value

(if

any)
.
The

previous

value

is

lost
.
￿



￿















￿
The asterisk (څ) indicates multiplication
Thi(
ڀ
⥩h

￿





ڀ
)

i
s
h
ﵡ
i
n
d
e
￿
The arithmetic operators are binary operators because
hhd
t
h
e
y
eac
h
operate on two operan
d
s.
￿
Integer divisionyields an integer quotient.
￿Any fractional part in integer division is simply discarded (i.e.,
truncated)—no rounding occurs.
Thidt
%
ildthidft
￿








%
,
yi
e
ld
s
th
e rema
i
n
d
er a
ft
er
division.
￿
ArithmeticexpressionsinJavamustbewrittenin
￿
Arithmetic

expressions

in

Java

must

be

written

in

straight-line formto facilitate entering programs into
the com
p
uter.
p
￿
Expressions such as “adivided by b” must be written
as a/b, so that all constants, variables and operators
appear in a strai
g
ht line.
￿
Parentheses are used to group terms in expressions in
hilbii
t
h
e same manner as
i
n a
lg
e
b
ra
i
c express
i
ons.
￿
If an expression contains nested parentheses, the
iithittfthi
express
i
on
i
n
th
e
i
nnermos
t
se
t
o
f
paren
th
eses
i
s
evaluated first.
￿
Rulesofoperatorprecedence
￿
Rules

of

operator

precedence
￿Multiplication, division and remainder operations are applied first.
￿If an expression contains several such operations, they are applied from
lefttoright
left

to

right
.
￿Multiplication, division and remainder operators have the same level of
precedence.
Addiidbiilid
￿
Addi
t
i
on an
d
su
b
tract
i
on operat
i
ons are app
li
e
d
next.
￿If an expression contains several such operations, the operators are
applied from left to right.
￿Addition and subtraction operators have the same level of precedence.
￿
When we say that operators are applied from left to right, we are
referringtotheir
associativity
.
referring

to

their

associativity
.

￿
Some operators associate from right to left.
￿
Complete precedence chart is included in AppendixA.
￿




￿






























￿
Condition
￿
Condition
￿An expression that can be 
or ێ.
￿
selection statement
￿Allows a program to make a decisionbased on a condition’s value.
￿
Equality operators(ژژand ټژ)
Rlil
(
d
)
￿
R
e
l
at
i
ona
l
operators
(
, , ژan
d
ژ
)

￿
Both equality operators have the same level of precedence,
whichislowerthanthatoftherelationaloperators
which

is

lower

than

that

of

the

relational

operators
.
￿
The equality operators associate from left to right.
￿
Therelationaloperatorsallhavethesamelevelof
￿
The

relational

operators

all

have

the

same

level

of

precedence and also associate from left to right.
￿
An
if
statementalwaysbeginswithkeyword
if
￿
An

if
statement

always

begins

with

keyword

if
,
followed by a condition in parentheses.
￿Ex
p
ects one statement in its bod
y,
but ma
y
contain multi
p
le
py,yp
statements if they are enclosed in a set of braces ({}).
￿The indentation of the body statement is not required, but it
improvestheprogram

sreadabilitybyemphasizingthat
improves

the

programs

readability

by

emphasizing

that

statements are part of the body.
￿
Note that there is no semicolon
(
;
)
at the end of the
(
;
)
first line of each ifstatement.
￿Such a semicolon would result in a logic error at execution
ti
ti
me.
￿Treated as the empty statement—semicolon by itself.