You are on page 1of 111

1

1992-2007 Pearson Education, Inc. All rights reserved.


Programming
Languages: Java
Instructor: Omer Boyaci
Lecture 1
Introduction to Java
2
1992-2007 Pearson Education, Inc. All rights reserved.
Course Information
History of Java
Introduction
First Program in Java: Printing a Line of Text
Modifying Our First Java Program
Dispaying Text !it" printf
#not"er Java #ppication: #dding Integers
Memory Concepts
#rit"metic
Decision Ma$ing: %&uaity and 'eationa Operators
Introduction to O()ect*oriented Programming
3
1992-2007 Pearson Education, Inc. All rights reserved.
Course Information
Six Lectures
Teaches Java Standart Edition 6
No midterm or final
Six assignments (5,!,5,"!,"5,"5#
htt$%&&'''(omer)o*aci(com&
Text)oo+
Java ,o' to -rogram, .th Edition, /eitel 0 /eitel
4
1992-2007 Pearson Education, Inc. All rights reserved.
Introduction
Java Standard Edition (Java SE# 6
Sun1s im$lementation called the Java /evelo$ment 2it
(J/2#
3)4ect53riented -rogramming
Java is language of choice for net'or+ed a$$lications
3$en Source
6rite 3nce 7un Ever*'here

1992-2007 Pearson Education, Inc. All rights reserved.


Mac"ine Languages+ #ssem(y
Languages and Hig"*Leve Languages
8achine language
Natural language of com$uter com$onent
8achine de$endent
9ssem)l* language
English5li+e a))reviations re$resent com$uter o$erations
Translator $rograms (assem)lers# convert to machine language
,igh5level language
9llo's for 'riting more English5li+e instructions
:ontains commonl* used mathematical o$erations
:om$iler converts to machine language
;nter$reter
Execute high5level language $rograms 'ithout com$ilation
!
1992-2007 Pearson Education, Inc. All rights reserved.
History of Java
Java
3riginall* for intelligent consumer5electronic devices
Then used for creating 'e) $ages 'ith d*namic content
No' also used to%
/evelo$ large5scale enter$rise a$$lications
Enhance 'e) server functionalit*
-rovide a$$lications for consumer devices (cell $hones, etc(#
7
1992-2007 Pearson Education, Inc. All rights reserved.
Java Patform
"
1992-2007 Pearson Education, Inc. All rights reserved.
Java ,tandart %dition -,%.
9
1992-2007 Pearson Education, Inc. All rights reserved.
Java %nterprise %dition -%%.
geared to'ard large5scale distri)uted a$$lications and 'e)
a$$lications
Enter$rise Java<eans (EJ<#
Servlets
Java Server -ages (JS-#
Java Server =aces (JS=#
Java8ail
Java Transaction 9-; (JT9#
10
1992-2007 Pearson Education, Inc. All rights reserved.
Java Micro %dition -M%.
geared to'ard a$$lications for small, memor* constrained
devices
8idlets
>oogle 8a$s 8o)ile
3$era 8ini
11
1992-2007 Pearson Education, Inc. All rights reserved.
Java Cass Li(raries
Java $rograms consist of classes
;nclude methods that $erform tas+s
7eturn information after tas+ com$letion
Java $rovides class li)raries
2no'n as Java 9-;s (9$$lication -rogramming
;nterfaces#
To use Java effectivel*, *ou must +no'
Java $rogramming language
Extensive class li)raries
12
1992-2007 Pearson Education, Inc. All rights reserved.
/se Java #PI casses
;m$rove $rogram $erformance
Shorten $rogram develo$ment time
-revent soft'are )ugs
;m$rove $rogram $orta)ilit*
13
1992-2007 Pearson Education, Inc. All rights reserved.
Typica Java Deveopment %nvironment
Java $rograms go through five $hases
Edit
-rogrammer 'rites $rogram using an editor? stores $rogram on dis+ 'ith
the .java file name extension
:om$ile
@se 4avac (the Java com$iler# to create )*tecodes from source code $rogram?
)*tecodes stored in .class files
Load
:lass loader reads )*tecodes from .class files into memor*
Aerif*
<*tecode verifier examines )*tecodes to ensure that the* are valid and do not
violate securit* restrictions
Execute
Java Airtual 8achine (JA8# uses a com)ination of inter$retation and 4ust5
in5time com$ilation to translate )*tecodes into machine language
14
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 101 2 Typica Java deveopment environment0
1
1992-2007 Pearson Education, Inc. All rights reserved.
Through the Java VM, the same application is
capable of running on multiple platforms.
1!
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text
9$$lication
Executes 'hen *ou use the java command to launch the
Java Airtual 8achine (JA8#
Sam$le $rogram
/is$la*s a line of text
;llustrates several im$ortant Java language features
17
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Welcome1.java
1 // Fig. 2.1: Welcome1.java
2 // Text-printing program.
%
& public class Welcome1
' {
( // main metho begins execution of !ava application
7 public static voi main" #tring args$% &
) {
9 #'stem.out.println" (Welcome to !ava )rogramming*( &+
10
11 , // en metho main
12
1% , // en cla-ss Welcome1

Welcome to !ava )rogramming*


1"
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
:omments start 'ith% //
:omments ignored during $rogram execution
/ocument and descri)e code
-rovides code reada)ilit*
Traditional comments% /. ... ./
/. This is a traitional
comment. /t can be
split over man' lines ./
9nother line of comments
Note% line num)ers not $art of $rogram, added for reference
1 // Fig. 2.1: Welcome1.java
3 // Text-printing program.
19
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
<lan+ line
8a+es $rogram more reada)le
<lan+ lines, s$aces, and ta)s are 'hite5s$ace characters
;gnored )* com$iler
<egins class declaration for class Welcome1
Ever* Java $rogram has at least one user5defined class
2e*'ord% 'ords reserved for use )* Java
class +e*'ord follo'ed )* class name
Naming classes% ca$italiBe ever* 'ord
#ample0lass1ame
4
5 public class Welcome1
20
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
Java identifier
Series of characters consisting of letters, digits,
underscores ( 2 # and dollar signs ( 3 #
/oes not )egin 'ith a digit, has no s$aces
Exam$les% Welcome1, 3value, 2value, button4
4button is invalid
Java is case sensitive (ca$italiBation matters#
a1 and 51 are different
5 public class Welcome1
21
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
Saving files
=ile name must )e class name 'ith .java extension
6 Welcome1.java
Left )race {
<egins )od* of ever* class
7ight )race ends declarations (line C#
5 public class Welcome1
6 {
22
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
-art of ever* Java a$$lication
9$$lications )egin executing at main
-arentheses indicate main is a method
Java a$$lications contain one or more methods
Exactl* one method must )e called main
8ethods can $erform tas+s and return information
6 voi means main returns no information
=or no', mimic mainDs first line
Left )race )egins )od* of method declaration
Ended )* right )race , (line #
7 public static voi main" #tring args$% &
8 {
23
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
;nstructs com$uter to $erform an action
-rints string of characters
String E series of characters inside dou)le Fuotes
6hite5s$aces in strings are not ignored )* com$iler
#'stem.out
Standard out$ut o)4ect
-rint to command 'indo' (i(e(, 8S5/3S $rom$t#
8ethod #'stem.out.println
/is$la*s line of text
This line +no'n as a statement
Statements must end 'ith semicolon +
9 #'stem.out.println" (Welcome to !ava )rogramming*( &+
24
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
Ends method declaration
Ends class declaration
:an add comments to +ee$ trac+ of ending )races
11 , // en metho main
14 , // en class Welcome1
2
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
:om$iling a $rogram
3$en a command $rom$t 'indo', go to director* 'here
$rogram is stored
T*$e javac Welcome1.java
;f no s*ntax errors, Welcome1.class created
,as )*tecodes that re$resent a$$lication
<*tecodes $assed to JA8

s*stem1s PATH environment varia)le for 4ava and 4avac


2!
1992-2007 Pearson Education, Inc. All rights reserved.
First Program in Java: Printing a Line of
Text -Cont0.
Executing a $rogram
T*$e java Welcome1
Launches JA8
JA8 loads .class file for class Welcome1
6
.class extension omitted from command
JA8 calls method main
27
1992-2007 Pearson Education, Inc. All rights reserved.
%xecuting Welcome1 in a Microsoft :indo!s ;P *ommand Prom+t !indo!0
,ou ty+e t$is command to e-ecute
t$e a++"ication
.$e +ro#ram out+uts
:ecome to Java Programming<
2"
1992-2007 Pearson Education, Inc. All rights reserved.
Modifying Our First Java Program
8odif* exam$le in =ig( "( to $rint same contents
using different code
29
1992-2007 Pearson Education, Inc. All rights reserved.
Modifying Our First Java Program -Cont0.
8odif*ing $rograms
Welcome2.java (=ig( "(C# $roduces same out$ut as
Welcome1.java (=ig( "(#
@sing different code
Line G dis$la*s 6elcome to 'ith cursor remaining on
$rinted line
Line ! dis$la*s Java -rogrammingH on same line 'ith
cursor on next line
9 #'stem.out.print" (Welcome to ( &+
1= #'stem.out.println" (!ava )rogramming*( &+
30
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Out"ine
Welcome2.java
1. 0omments
2. 7lan8 line
9. 7egin class
Welcome2
9.1 :etho main
;. :etho
#'stem.out.print
;.1 :etho
#'stem.out.print
ln
<. en main=
Welcome2
)rogram >utput
1 // Fig. 2.9: Welcome2.java
2 // )rinting a line of text ?ith multiple statements.
%
& public class Welcome2
' {
( // main metho begins execution of !ava application
7 public static voi main" #tring args$% &
) {
9 #'stem.out.print" (Welcome to ( &+
10 #'stem.out.println" (!ava )rogramming*( &+
11
12 , // en metho main
1%
1& , // en class Welcome2

Welcome to !ava )rogramming*


#'stem.out.print #ee$s the cursor on
the sa%e line, so #'stem.out.println
continues on the sa%e line.
31
1992-2007 Pearson Education, Inc. All rights reserved.
Modifying Our First Java Program -Cont0.
Esca$e characters
<ac+slash ( @ #
;ndicates s$ecial characters to )e out$ut
Ne'line characters (@n#
;nter$reted as s$ecial characters )* methods
#'stem.out.print and #'stem.out.println
;ndicates cursor should )e at the )eginning of the next line
Welcome9.java (=ig( "(I#
Line )rea+s at @n
9 #'stem.out.println" (Welcome@nto@n!ava@n)rogramming*( &+
32
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Out"ine
Welcome9.java
1. main
2.
#'stem.out.println
"uses @n for ne?
line&
)rogram >utput
1 // Fig. 2.;: Welcome9.java
2 // )rinting multiple lines of text ?ith a single statement.
%
& public class Welcome9
' {
( // main metho begins execution of !ava application
7 public static voi main" #tring args$% &
) {
9 #'stem.out.println" (Welcome@nto@n!ava@n)rogramming*( &+
10
11 , // en metho main
12
1% , // en class Welcome9
Welcome
to
!ava
)rogramming*

A ne& line 'egins a(ter each @n esca$e
se)uence is out$ut.
33
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 306 2 ,ome common escape se&uences0
%scape
se&uence
Description
@n *e&line. Position the screen cursor at the 'eginning o( the ne+t line.
@t ,ori-ontal ta'. .ove the screen cursor to the ne+t ta' sto$.
@r /arriage return. Position the screen cursor at the 'eginning o( the
current line0do not advance to the ne+t line. An1 characters out$ut
a(ter the carriage return over&rite the characters $reviousl1 out$ut
on that line.
@@
2ac#slash. 3sed to $rint a 'ac#slash character.
@( 4ou'le )uote. 3sed to $rint a dou'le-)uote character. 5or e+a%$le,
#'stem.out.println" (@(in Auotes@(( &+
dis$la1s
(in Auotes(

34
1992-2007 Pearson Education, Inc. All rights reserved.
Dispaying Text !it" printf
6#'stem.out.printf
=eature added in Java SE 5(!
/is$la*s formatted data
=ormat string
=ixed text
=ormat s$ecifier E $laceholder for a value
=ormat s$ecifier Bs E $laceholder for a string
9 #'stem.out.printf" (Bs@nBs@n(=
1= (Welcome to(= (!ava )rogramming*( &+
3
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Out"ine
Welcome;.java
main
printf
)rogram output
1 // Fig. 2.C: Welcome;.java
2 // )rinting multiple lines in a ialog box.
%
& public class Welcome;
' {
( // main metho begins execution of !ava application
7 public static voi main" #tring args$% &
) {
9 #'stem.out.printf" (Bs@nBs@n(=
10 (Welcome to(= (!ava )rogramming*( &+
11
12 , // en metho main
1%
1& , // en class Welcome;

Welcome to
!ava )rogramming*


#'stem.out.printf
dis$la1s (or%atted data.
3!
1992-2007 Pearson Education, Inc. All rights reserved.
#not"er Java #ppication: #dding
Integers
@$coming $rogram
@se #canner to read t'o integers from user
@se printf to dis$la* sum of the t'o values
@se $ac+ages
37
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Out"ine
5ition.java
61 o( 27
import declaration
#canner
next/nt
1 // Fig. 2.4: 5ition.java
2 // 5ition program that ispla's the sum of t?o numbers.
% import java.util.#canner+ // program uses class #canner
&
' public class 5ition
( {
7 // main metho begins execution of !ava application
) public static voi main" #tring args$% &
9 {
10 // create #canner to obtain input from comman ?ino?
11 #canner input D ne? #canner" #'stem.in &+
12
1% int number1+ // first number to a
1& int number2+ // secon number to a
1' int sum+ // sum of number1 an number2
1(
17 #'stem.out.print" (Enter first integer: ( &+ // prompt
1) number1 D input.next/nt"&+ // rea first number from user
19

import declaration i%$orts class
#canner (ro% $ac#age java.util.
4eclare and initiali-e varia'le
input, &hich is a #canner.
4eclare varia'les number1,
number2 and sum.
8ead an integer (ro% the user
and assign it to number1.
3"
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Out"ine
5ition.java
62 o( 27
4. Addition
. printf
20 #'stem.out.print" (Enter secon integer: ( &+ // prompt
21 number2 D input.next/nt"&+ // rea secon number from user
22
2% sum D number1 F number2+ // a numbers
2&
2' #'stem.out.printf" (#um is B@n(= sum &+ // ispla' sum
2(
27 , // en metho main
2)
29 , // en class 5ition

Enter first integer: ;<
Enter secon integer: 42
#um is 114


8ead an integer (ro% the user
and assign it to number2.
/alculate the su% o( the
varia'les number1 and
number2, assign result to sum.
4is$la1 the su% using
(or%atted out$ut.
9&o integers entered '1 the user.
39
1992-2007 Pearson Education, Inc. All rights reserved.
#not"er Java #ppication: #dding
Integers -Cont0.
import declarations
@sed )* com$iler to identif* and locate classes used in Java
$rograms
Tells com$iler to load class #canner from java.util
$ac+age
<egins public class 5ition
7ecall that file name must )e 5ition.java
Lines .5G% )egin main
4 import java.util.#canner+ // program uses class #canner
< public class 5ition
C {
40
1992-2007 Pearson Education, Inc. All rights reserved.
#not"er Java #ppication: #dding
Integers -Cont0.
Aaria)le /eclaration Statement
Aaria)les
Location in memor* that stores a value
/eclare 'ith name and t*$e )efore use
6 /nput is of t*$e #canner
Ena)les a $rogram to read data for use
Aaria)le name% an* valid identifier
/eclarations end 'ith semicolons +
;nitialiBe varia)le in its declaration
EFual sign
Standard in$ut o)4ect
#'stem.in
1G // create #canner to obtain input from comman ?ino?
11 #canner input D ne? #canner" #'stem.in &+
41
1992-2007 Pearson Education, Inc. All rights reserved.
#not"er Java #ppication: #dding
Integers -Cont0.
/eclare varia)le number1, number2 and sum of t*$e int
6 int holds integer values ('hole num)ers#% i(e(, G, -;, H4
T*$es float and ouble can hold decimal num)ers
T*$e char can hold a single character% i(e(, x, J, Kn, L
6 int, float, ouble and char are $rimitive t*$es
:an add comments to descri)e $ur$ose of varia)les
:an declare multi$le varia)les of the same t*$e in one
declaration
@se comma5se$arated list
14 int number1+ // first number to a
15 int number2+ // secon number to a
16 int sum+ // sum of number 1 an number 2
int number1= // first number to a
number2= // secon number to a
sum+ // sum of number1 an number2
42
1992-2007 Pearson Education, Inc. All rights reserved.
#not"er Java #ppication: #dding
Integers -Cont0.
8essage called a $rom$t 5 directs user to $erform an
action
-ac+age java.lang
7esult of call to next/nt given to number1 using
assignment o$erator D
9ssignment statement
6
D )inar* o$erator 5 ta+es t'o o$erands
Ex$ression on right evaluated and assigned to varia)le
on left
7ead as% number1 gets the value of input.next/nt"&
17 #'stem.out.print" (Enter first integer: ( &+ // prompt
18 number1 D input.next/nt"&+ // rea first number from user
43
1992-2007 Pearson Education, Inc. All rights reserved.
#not"er Java #ppication: #dding
Integers -Cont0.
Similar to $revious statement
-rom$ts the user to in$ut the second integer
Similar to $revious statement
9ssign varia)le num)er" to second integer in$ut
9ssignment statement
:alculates sum of number1 and number2 (right hand side#
@ses assignment o$erator D to assign result to varia)le sum
7ead as% sum gets the value of number1 F number2
6 number1 and number2 are o$erands
3= #'stem.out.print" (Enter secon integer: ( &+ // prompt
31 number2 D input.next/nt"&+ // rea secon number from user
34 sum D number1 F number2+ // a numbers
44
1992-2007 Pearson Education, Inc. All rights reserved.
#not"er Java #ppication: #dding
Integers -Cont0.
@se #'stem.out.printf to dis$la* results
=ormat s$ecifier B
-laceholder for an int value
:alculations can also )e $erformed inside printf
-arentheses around the ex$ression number1 M number2
are not reFuired
36 #'stem.out.printf" (#um is B@n ( = sum &+ // ispla' sum
#'stem.out.printf" (#um is B@n ( = " number1 F number2 & &+
4
1992-2007 Pearson Education, Inc. All rights reserved.
Memory Concepts
Variables
Every variable has a name, a type, a size and a value
Name corresponds to location in memory
When new value is placed into a variable, replaces (and
destroys) previous value
Reading variables from memory does not change them
4!
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 308 2 Memory ocation s"o!ing t"e name and vaue of varia(e number1.
47
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 309 2 Memory ocations after storing vaues for number1 and number2.
4"
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 301= 2 Memory ocations after cacuating and storing t"e sum of number1 and
number20
49
1992-2007 Pearson Education, Inc. All rights reserved.
#rit"metic
9rithmetic calculations used in most $rograms
@sage
6
. for multi$lication
6
/ for division
6
B for remainder
6
F, -
;nteger division truncates remainder
4 / < evaluates to 1
7emainder o$erator B returns the remainder
4 B < evaluates to 2
0
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 3011 2 #rit"metic operators0
Java
operation
#rit"metic
operator
#ge(raic
expression
Java
expression
Addition
F
f : 7
f F 4
;u'traction
I
p < c
p - c
.ulti$lication
.
bm
b . m
4ivision
/
x = y or or x > y

x / '

1
1992-2007 Pearson Education, Inc. All rights reserved.
#rit"metic -Cont0.
3$erator $recedence
Some arithmetic o$erators act )efore others (i(e(,
multi$lication )efore addition#
@se $arenthesis 'hen needed
Exam$le% =ind the average of three varia)les a, b and c
/o not use% a F b F c / 9
@se% " a F b F c & / 9
2
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 3013 2 Precedence of arit"metic operators0
Operator-s. Operation-s. Order of evauation
-precedence.
.
/
B
.ulti$lication
4ivision
8e%ainder
Evaluated (irst. I( there are
several o$erators o( this t1$e,
the1 are evaluated (ro% le(t to
right.
F
-
Addition
;u'traction
Evaluated ne+t. I( there are
several o$erators o( this t1$e,
the1 are evaluated (ro% le(t to
right.

3
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 3014 2 Order in !"ic" a second*degree poynomia is evauated0
4
1992-2007 Pearson Education, Inc. All rights reserved.
Decision Ma$ing: %&uaity and 'eationa
Operators
:ondition
Ex$ression can )e either true or false
6
if statement
Sim$le version in this section, more detail later
;f a condition is true, then the )od* of the if statement
executed
:ontrol al'a*s resumes after the if statement
:onditions in if statements can )e formed using eFualit*
or relational o$erators (next slide#

1992-2007 Pearson Education, Inc. All rights reserved.


Fig0 3015 2 %&uaity and reationa operators0
,tandard age(raic
e&uaity or reationa
operator
Java e&uaity
or reationa
operator
,ampe
Java
condition

Meaning of
Java condition
Equality operators
= DD
x DD '
x is e)ual to '

*D x *D '
x is not e)ual to '
Relational operators


>
J x J '
x is greater than '
<
K x K '
x is less than '

JD x JD '
x is greater than or e)ual to '
?
KD x KD '
x is less than or e)ual to '

!
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Out"ine
0omparison.java
61 o( 27
1. 0lass
0omparison
1.1 main
1.2 Leclarations
1.9 /nput ata
"next/nt&
1.; 0ompare t?o
inputs using if
statements
1 // Fig. 2.1<: 0omparison.java
2 // 0ompare integers using if statements= relational operators
% // an eAualit' operators.
& import java.util.#canner+ // program uses class #canner
'
( public class 0omparison
7 {
) // main metho begins execution of !ava application
9 public static voi main" #tring args$% &
10 {
11 // create #canner to obtain input from comman ?ino?
12 #canner input D ne? #canner" #'stem.in &+
1%
1& int number1+ // first number to compare
1' int number2+ // secon number to compare
1(
17 #'stem.out.print" (Enter first integer: ( &+ // prompt
1) number1 D input.next/nt"&+ // rea first number from user
19
20 #'stem.out.print" (Enter secon integer: ( &+ // prompt
21 number2 D input.next/nt"&+ // rea secon number from user
22
2% if " number1 DD number2 &
2& #'stem.out.printf" (B DD B@n(= number1= number2 &+
2'
2( if " number1 *D number2 &
27 #'stem.out.printf" (B *D B@n(= number1= number2 &+
2)
29 if " number1 K number2 &
%0 #'stem.out.printf" (B K B@n(= number1= number2 &+

9est (or e)ualit1, dis$la1
result using printf.
/o%$ares t&o nu%'ers
using relational o$erator K.
7
1992-2007 Pearson Education, Inc !"" ri#$ts reserved
Out"ine
0omparison.java
62 o( 27
Progra% out$ut
%1
%2 if " number1 J number2 &
%% #'stem.out.printf" (B J B@n(= number1= number2 &+
%&
%' if " number1 KD number2 &
%( #'stem.out.printf" (B KD B@n(= number1= number2 &+
%7
%) if " number1 JD number2 &
%9 #'stem.out.printf" (B JD B@n(= number1= number2 &+
&0
&1 , // en metho main
&2
&% , // en class 0omparison

Enter first integer: 444
Enter secon integer: 444
444 DD 444
444 KD 444
444 JD 444


Enter first integer: 1GGG
Enter secon integer: 2GGG
1GGG *D 2GGG
1GGG K 2GGG
1GGG KD 2GGG



Enter first integer: 2GGG
Enter secon integer: 1GGG
2GGG *D 1GGG
2GGG J 1GGG
2GGG JD 1GGG


/o%$ares t&o nu%'ers
using relational o$erators
J, KD and JD.
"
1992-2007 Pearson Education, Inc. All rights reserved.
Decision Ma$ing: %&uaity and 'eationa
Operators -Cont0.
Line 6% )egins class 0omparison declaration
Line "% declares Scanner varia)le in$ut and assigns it a
Scanner that in$uts data from the standard in$ut
Lines I55% declare int varia)les
Lines L5.% $rom$t the user to enter the first integer and
in$ut the value
Lines "!5"% $rom$t the user to enter the second integer
and in$ut the value
9
1992-2007 Pearson Education, Inc. All rights reserved.
Decision Ma$ing: %&uaity and 'eationa
Operators -Cont0.
if statement to test for eFualit* using (DD#
;f varia)les eFual (condition true#
Line "I executes
;f varia)les not eFual, statement s+i$$ed
No semicolon at the end of line "C
Em$t* statement
No tas+ is $erformed
Lines "65"L, "G5C!, C"5CC, C55C6 and C.5CG
:om$are number1 and number2 'ith the o$erators *D, K,
J, KD and JD, res$ectivel*
34 if " number1 DD number2 &
35 #'stem.out.printf" (B DD B@n(= number1= number2 &+
!0
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 301> 2 Precedence and associativity of operations discussed0
Operators #ssociativity Type
. / B
le(t to right %ulti$licative
F -
le(t to right additive
K KD J JD
le(t to right relational
DD *D
le(t to right e)ualit1
D
right to le(t assign%ent

!1
1992-2007 Pearson Education, Inc. All rights reserved.
O()ect*oriented Programming
3)4ects
7eusa)le soft'are com$onents that model real5'orld items
Loo+ all around *ou
-eo$le, animals, $lants, cars, etc(
9ttri)utes
SiBe, sha$e, color, 'eight, etc(
<ehaviors
<a)ies cr*, cra'l, slee$, etc(
!2
1992-2007 Pearson Education, Inc. All rights reserved.
O()ect*oriented Programming
3)4ect5oriented design (33/#
8odels soft'are in terms similar to those used to descri)e real5
'orld o)4ects
:lass relationshi$s
;nheritance relationshi$s
8odels communication among o)4ects
Enca$sulates attri)utes and o$erations ()ehaviors#
;nformation hiding
:ommunication through 'ell5defined interfaces
3)4ect5oriented language
-rogramming in o)4ect5oriented languages is called object-
oriented programming (OOP#
Java
!3
1992-2007 Pearson Education, Inc. All rights reserved.
O()ect*oriented Programming
:lasses are to o)4ects as )lue$rints are to houses
9ssociations
7elationshi$s )et'een classes
-ac+aging soft'are in classes facilitates reuse
!4
1992-2007 Pearson Education, Inc. All rights reserved.
O()ect*oriented Programming
3)4ect53riented 9nal*sis and /esign (339&/#
Essential for large $rograms
9nal*Be $rogram reFuirements, then develo$ a design
@8L
@nified 8odeling Language
Standard for designing o)4ect5oriented s*stems
!
1992-2007 Pearson Education, Inc. All rights reserved.
O()ect*oriented Programming
,istor* of the @8L
Need develo$ed for $rocess 'ith 'hich to a$$roach 339&
/
<rainchild of <ooch, 7um)augh and Jaco)son
3)4ect 8anagement >rou$ (38># su$ervised
Aersion " is current version
!!
1992-2007 Pearson Education, Inc. All rights reserved.
O()ect*oriented Programming
@8L
>ra$hical re$resentation scheme
Ena)les develo$ers to model o)4ect5oriented s*stems
=lexi)le and extensi)le
!7
1992-2007 Pearson Education, Inc. All rights reserved.
*ontro" /tatements
!"
1992-2007 Pearson Education, Inc. All rights reserved.
Introduction
#gorit"ms
Pseudocode
Contro ,tructures
if ,inge*,eection ,tatement
ifMelse Dou(e*,eection ,tatement
?hile 'epetition ,tatement
Formuating #gorit"ms: Counter*Controed 'epetition
Formuating #gorit"ms: ,entine*Controed 'epetition
Formuating #gorit"ms: ?ested Contro ,tatements
Compound #ssignment Operators
Increment and Decrement Operators
Primitive Types
!9
1992-2007 Pearson Education, Inc. All rights reserved.
#gorit"ms
9lgorithms
The actions to execute
The order in 'hich these actions execute
-rogram control
S$ecifies the order in 'hich actions execute in a
$rogram
70
1992-2007 Pearson Education, Inc. All rights reserved.
Pseudocode
-seudocode
9n informal language similar to English
,el$s $rogrammers develo$ algorithms
/oes not run on com$uters
Should contain in$ut, out$ut and calculation actions
Should not contain varia)le declarations
71
1992-2007 Pearson Education, Inc. All rights reserved.
Contro ,tructures
SeFuential execution
Statements are normall* executed one after the other in the
order in 'hich the* are 'ritten
Transfer of control
S$ecif*ing the next statement to execute that is not
necessaril* the next one in order
:an )e $erformed )* the goto statement
Structured $rogramming eliminated goto statements
72
1992-2007 Pearson Education, Inc. All rights reserved.
Contro ,tructures -Cont0.
<ohm and Jaco$ini1s research
/emonstrated that goto statements 'ere unnecessar*
/emonstrated that all $rograms could )e 'ritten 'ith
three control structures
The seFuence structure,
The selection structure and
The re$etition structure
73
1992-2007 Pearson Education, Inc. All rights reserved.
Contro ,tructures -Cont0.
@8L activit* diagram ('''(uml(org#
8odels the 'or+flo' (or activit*# of a $art of a soft'are
s*stem
9ction5state s*m)ols (rectangles 'ith their sides re$laced
'ith out'ard5curving arcs#
re$resent action ex$ressions s$ecif*ing actions to $erform
/iamonds
/ecision s*m)ols
8erge s*m)ols
74
1992-2007 Pearson Education, Inc. All rights reserved.
Contro ,tructures -Cont0.
Small circles
Solid circle re$resents the activit*1s initial state
Solid circle surrounded )* a hollo' circle re$resents the
activit*1s final state
Transition arro's
;ndicate the order in 'hich actions are $erformed
Notes (rectangles 'ith the u$$er5right corners folded over#
Ex$lain the $ur$oses of s*m)ols (li+e comments in Java#
9re connected to the s*m)ols the* descri)e )* dotted lines
7
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 501 2 ,e&uence structure activity diagram0
7!
1992-2007 Pearson Education, Inc. All rights reserved.
Contro ,tructures -Cont0.
Selection Statements
if statement
Single5selection statement
ifelse statement
/ou)le5selection statement
switch statement
8ulti$le5selection statement
77
1992-2007 Pearson Education, Inc. All rights reserved.
Contro ,tructures -Cont0.
7e$etition statements
9lso +no'n as loo$ing statements
7e$eatedl* $erforms an action 'hile its loo$5continuation
condition remains true
while statement
-erforms the actions in its )od* Bero or more times
dowhile statement
-erforms the actions in its )od* one or more times
for statement
-erforms the actions in its )od* Bero or more times
7"
1992-2007 Pearson Education, Inc. All rights reserved.
Contro ,tructures -Cont0.
Java has three +inds of control structures
SeFuence statement,
Selection statements (three t*$es# and
7e$etition statements (three t*$es#
9ll $rograms are com$osed of these control statements
:ontrol5statement stac+ing
9ll control statements are single5entr*&single5exit
:ontrol5statement nesting
79
1992-2007 Pearson Education, Inc. All rights reserved.
if ,inge*,eection ,tatement

if statements
Execute an action if the s$ecified condition is true
:an )e re$resented )* a decision s*m)ol (diamond# in a
@8L activit* diagram
Transition arro's out of a decision s*m)ol have guard
conditions
6or+flo' follo's the transition arro' 'hose guard
condition is true
"0
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 503 2 if singe*seection statement /ML activity diagram0
"1
1992-2007 Pearson Education, Inc. All rights reserved.
ifelse Dou(e*,eection ,tatement

ifelse statement
Executes one action if the s$ecified condition is true or a
different action if the s$ecified condition is false
:onditional 3$erator ( ? : #
Java1s onl* ternar* o$erator (ta+es three o$erands#
? : and its three o$erands form a conditional ex$ression
Entire conditional ex$ression evaluates to the second
o$erand if the first o$erand is true
Entire conditional ex$ression evaluates to the third o$erand
if the first o$erand is false
"2
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 504 2 if@ese dou(e*seection statement /ML activity diagram0
"3
1992-2007 Pearson Education, Inc. All rights reserved.
ifelse Dou(e*,eection ,tatement
-Cont0.
Nested ifelse statements
ifelse statements can )e $ut inside other ifelse
statements
/angling5else $ro)lem
elses are al'a*s associated 'ith the immediatel*
$receding if unless other'ise s$ecified )* )races { }
<loc+s
<races { } associate statements into )loc+s
<loc+s can re$lace individual statements as an if )od*
"4
1992-2007 Pearson Education, Inc. All rights reserved.
ifelse Dou(e*,eection ,tatement
-Cont0.
Logic errors
=atal logic errors cause a $rogram to fail and terminate
$rematurel*
Nonfatal logic errors cause a $rogram to $roduce incorrect
results
Em$t* statements
7e$resented )* $lacing a semicolon ( ; # 'here a statement
'ould normall* )e
:an )e used as an if )od*
"
1992-2007 Pearson Education, Inc. All rights reserved.
Aood Programming Practice 505
9l'a*s using )races in an if...else (or
other# statement hel$s $revent their
accidental omission, es$eciall* 'hen
adding statements to the if5$art or the
else5$art at a later time( To avoid omitting
one or )oth of the )races, some
$rogrammers t*$e the )eginning and
ending )races of )loc+s )efore t*$ing the
individual statements 'ithin the )races(
"!
1992-2007 Pearson Education, Inc. All rights reserved.
'epetition ,tatement
6
?hile statement
7e$eats an action 'hile its loo$5continuation condition
remains true
@ses a merge s*m)ol in its @8L activit* diagram
8erges t'o or more 'or+flo's
7e$resented )* a diamond (li+e decision s*m)ols# )ut has%
8ulti$le incoming transition arro's,
3nl* one outgoing transition arro' and
No guard conditions on an* transition arro's
"7
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 505 2 ?hile repetition statement /ML activity diagram0
""
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: Counter*
Controed 'epetition
:ounter5controlled re$etition
@se a counter varia)le to count the num)er of times a loo$
is iterated
;nteger division
The fractional $art of an integer division calculation is
truncated (thro'n a'a*#
"9
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 506 2 Pseudocode agorit"m t"at uses counter*controed repetition to sove t"e
cass*average pro(em0
1 Set total to zero
2 Set grade counter to one
3
4 While grade counter i le than or e!ual to ten
" Prompt the uer to enter the ne#t grade
$ %nput the ne#t grade
& Add the grade into the total
' Add one to the grade counter
(
1) Set the cla a*erage to the total di*ided b+ ten
11 Print the cla a*erage
90
1992-2007 Pearson Education, Inc. All rights reserved.
@rade2oo#.Aava
91
1992-2007 Pearson Education, Inc. All rights reserved.
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture134ava 5radeBoo2
Enter #rade: 12
Enter #rade: )
Enter #rade: 12
Enter #rade: 12
Enter #rade: %
Enter #rade: '
Enter #rade: (
Enter #rade: )
Enter #rade: 9
Enter #rade: (
.ota" o6 a"" 10 #rades is )1
*"ass avera#e is )
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture13
92
1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming %rror 506
9ssuming that integer division rounds
(rather than truncates# can lead to
incorrect results( =or exam$le, L N I,
'hich *ields (L5 in conventional
arithmetic, truncates to in integer
arithmetic, rather than rounding to "(
93
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: ,entine*
Controed 'epetition
Sentinel5controlled re$etition
9lso +no'n as indefinite re$etition
@se a sentinel value (also +no'n as a signal, dumm* or flag
value#
9 sentinel value cannot also )e a valid in$ut value
94
1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming %rror 50>
:hoosing a sentinel value that is also a
legitimate data value is a logic error(
9
1992-2007 Pearson Education, Inc. All rights reserved.
%rror*Prevention Tip 503
6hen $erforming division )* an
ex$ression 'hose value could )e Bero,
ex$licitl* test for this $ossi)ilit* and
handle it a$$ro$riatel* in *our $rogram
(e(g(, )* $rinting an error message#
rather than allo' the error to occur
9!
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 508 2 Cass*average pro(em pseudocode agorit"m !it" sentine*controed repetition0
1 %nitialize total to zero
2 %nitialize counter to zero
3
4 Prompt the uer to enter the ,irt grade
" %nput the ,irt grade -poibl+ the entinel.
$
& While the uer ha not +et entered the entinel
' Add thi grade into the running total
( Add one to the grade counter
1) Prompt the uer to enter the ne#t grade
11 %nput the ne#t grade -poibl+ the entinel.
12
13 %, the counter i not e!ual to zero
14 Set the a*erage to the total di*ided b+ the counter
1" Print the a*erage
1$ ele
1& Print /0o grade 1ere entered2
97
1992-2007 Pearson Education, Inc. All rights reserved.
9"
1992-2007 Pearson Education, Inc. All rights reserved.
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture134ava 5radeBoo27$i"e
Enter #rade or -1 to 8uit: %&
Enter #rade or -1 to 8uit: 1(
Enter #rade or -1 to 8uit: '
Enter #rade or -1 to 8uit: -1
.ota" o6 a"" 10 #rades is ''
*"ass avera#e is 1)%%
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture13
99
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: ,entine*
Controed 'epetition -Cont0.
@nar* cast o$erator
:reates a tem$orar* co$* of its o$erand 'ith a different
data t*$e
exam$le% (doule! 'ill create a tem$orar* floating5$oint
co$* of its o$erand
Ex$licit conversion
-romotion
:onverting a value (e(g( int# to another data t*$e (e(g(
doule# to $erform a calculation
;m$licit conversion
100
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: ?ested Contro
,tatements
:ontrol statements can )e nested 'ithin one
another
-lace one control statement inside the )od* of the other
101
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5011 2 Pseudocode for examination*resuts pro(em0
1 %nitialize pae to zero
2 %nitialize ,ailure to zero
3 %nitialize tudent counter to one
4
5 While tudent counter i le than or e!ual to 1)
6 Prompt the uer to enter the ne#t e#am reult
7 %nput the ne#t e#am reult
8
9 %, the tudent paed
10 Add one to pae
11 3le
12 Add one to ,ailure
13
14 Add one to tudent counter
15
16 Print the number o, pae
17 Print the number o, ,ailure
18
19 %, more than eight tudent paed
20 Print /4aie tuition2

102
1992-2007 Pearson Education, Inc. All rights reserved.
103
1992-2007 Pearson Education, Inc. All rights reserved.
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture134ava !na"ysis
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 2
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Passed: 9
<ai"ed: 1
=ard>or2in# c"ass
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture13
104
1992-2007 Pearson Education, Inc. All rights reserved.
Compound #ssignment Operators
:om$ound assignment o$erators
9n assignment statement of the form%
*ariable " *ariable operator e#preion;
'here operator is #, -, $, / or % can )e 'ritten as%
*ariable operator" e#preion;
exam$le% c " c # &; can )e 'ritten as c #" &;
This statement adds & to the value in varia)le c and stores
the result in varia)le c
10
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5015 2 #rit"metic compound assignment operators0
#ssignment
operator
,ampe
expression
%xpanation #ssigns
Aume5 int c D 9= D <= e D ;= f D C= g D 12+
FD c FD 4 0 D c F 4 1G to c
-D -D ; D - ; 1 to
.D e .D < e D e . < 2G to e
/D f /D 9 f D f / 9 2 to f
BD g BD H g D g B H 9 to g

10!
1992-2007 Pearson Education, Inc. All rights reserved.
Increment and Decrement Operators
@nar* increment and decrement o$erators
@nar* increment o$erator (### adds one to its o$erand
@nar* decrement o$erator (--# su)tracts one from its
o$erand
-refix increment (and decrement# o$erator
:hanges the value of its o$erand, then uses the ne' value of
the o$erand in the ex$ression in 'hich the o$eration a$$ears
-ostfix increment (and decrement# o$erator
@ses the current value of its o$erand in the ex$ression in
'hich the o$eration a$$ears, then changes the value of the
o$erand
107
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5016 2 Increment and decrement operators0
Operator Caed
,ampe
expression
%xpanation
FF
$refix
increment
FFa
;ncrement a )* 1, then use the ne' value of a in the
ex$ression in 'hich a resides(
FF
$ostfix
increment
aFF
@se the current value of a in the ex$ression in 'hich a resides,
then increment a )* 1(
--
$refix
decrement
--b
/ecrement b )* 1, then use the ne' value of b in the
ex$ression in 'hich b resides(
--
$ostfix
decrement
b--
@se the current value of b in the ex$ression in 'hich b resides,
then decrement b )* 1(

10"
1992-2007 Pearson Education, Inc. All rights reserved.
Outine

Incre%ent.Aa
va
1 // Fig. ;.1C: /ncrement.java
2 // )refix increment an postfix increment operators.
3
4 public class /ncrement
{
! public static voi main" #tring args$% &
7 {
" int c+
9
10 // emonstrate postfix increment operator
11 c D <+ // assign < to c
12 #'stem.out.println" c &+ // print <
13 #'stem.out.println" cFF &+ // print < then postincrement
14 #'stem.out.println" c &+ // print C
1
1! #'stem.out.println"&+ // s8ip a line
17
1" // emonstrate prefix increment operator
19 c D <+ // assign < to c
20 #'stem.out.println" c &+ // print <
21 #'stem.out.println" FFc &+ // preincrement then print C
22 #'stem.out.println" c &+ // print C
23
24 , // en main
2
2! , // en class /ncrement

<
<
C

<
C
C


Postincre%enting the c varia'le
Preincre%enting the c varia'le
109
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5017 2 Precedence and associativity of t"e operators discussed so far0
Operators #ssociativity Type
FF -- right to left unar* $ostfix
FF -- F - " t+pe & right to left unar* $refix
. / B left to right 8ulti$licative
F - left to right 9dditive
K KD J JD left to right 7elational
DD *D left to right EFualit*
N: right to left :onditional
D FD -D .D /D BD right to left assignment

110
1992-2007 Pearson Education, Inc. All rights reserved.
Primitive Types
Java is a strongl* t*$ed language
9ll varia)les have a t*$e
-rimitive t*$es in Java are $orta)le across all
$latforms that su$$ort Java
111
1992-2007 Pearson Education, Inc. All rights reserved.
Porta(iity Tip 501
@nli+e : and :MM, the $rimitive t*$es in
Java are $orta)le across all com$uter
$latforms that su$$ort Java( Than+s to this
and JavaDs man* other $orta)ilit* features,
a $rogrammer can 'rite a $rogram once
and )e certain that it 'ill execute on an*
com$uter $latform that su$$orts Java( This
ca$a)ilit* is sometimes referred to as WO4A
(6rite 3nce, 7un 9n*'here#(

You might also like