SlideShare a Scribd company logo
1 of 39
Download to read offline
Week 2
Data and
Expressions
© 2004 Pearson Addison-Wesley. All rights reserved 2-2
Data and Expressions
• Let's explore some other fundamental
programming concepts
• Chapter 2 focuses on:
 character strings
 primitive data
 the declaration and use of variables
 expressions and operator precedence
 data conversions
 accepting input from the user
© 2004 Pearson Addison-Wesley. All rights reserved 2-3
Copyright Warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been copied and communicated to you by or
on behalf of Bond University pursuant to Part VB of the
Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
under the Act. Any further copying or communication of this
material by you may be the subject of copyright protection
under the Act.
Do not remove this notice.
© 2004 Pearson Addison-Wesley. All rights reserved 2-4
Character Strings
• A string of characters can be represented as a
string literal by putting double quotes around the
text:
• Examples:
"This is a string literal."
"123 Main Street"
"X"
• Every character string is an object in Java, defined
by the String class
• Every string literal represents a String object
© 2004 Pearson Addison-Wesley. All rights reserved 2-5
The println Method
• In the Lincoln program from Chapter 1, we
invoked the println method to print a character
string
• The System.out object represents a destination
(the monitor screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");
objec
t
method
name information provided to the
method
(parameters)
© 2004 Pearson Addison-Wesley. All rights reserved 2-6
The print() Method
• The System.out object provides another service
as well
• The print method is similar to the println
method, except that it does not advance to the
next line
• Therefore anything printed after a print
statement will appear on the same line
• See Countdown.java (page 63)
© 2004 Pearson Addison-Wesley. All rights reserved 2-7
String Concatenation
• The string concatenation operator (+) is used to
append one string to the end of another
"Peanut butter " + "and jelly"
• It can also be used to append a number to a string
• A string literal cannot be broken across two lines
in a program
• See Facts.java (page 65)
© 2004 Pearson Addison-Wesley. All rights reserved 2-8
String Concatenation
• The + operator is also used for arithmetic addition
• The function that it performs depends on the type
of the information on which it operates
• If both operands are strings, or if one is a string
and one is a number, it performs string
concatenation
• If both operands are numeric, it adds them
• The + operator is evaluated left to right, but
parentheses can be used to force the order
• See Addition.java (page 67)
© 2004 Pearson Addison-Wesley. All rights reserved 2-9
Escape Sequences
• What if we wanted to print the quote character?
• The following line would confuse the compiler
because it would interpret the second quote as the
end of the string
System.out.println ("I said "Hello" to you.");
• An escape sequence is a series of characters that
represents a special character
• An escape sequence begins with a backslash
character ()
System.out.println ("I said "Hello" to you.");
© 2004 Pearson Addison-Wesley. All rights reserved 2-10
Escape Sequences
• Some Java escape sequences:
• See Roses.java (page 68)
Escape Sequence
b
t
n
r
"
'

Meaning
backspace
tab
newline
carriage return
double quote
single quote
backslash
© 2004 Pearson Addison-Wesley. All rights reserved 2-11
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Graphics
Applets
Drawing Shapes
© 2004 Pearson Addison-Wesley. All rights reserved 2-12
Variables
• A variable is a name for a location in memory
• A variable must be declared by specifying the
variable's name and the type of information that it
will hold
int total;
int count, temp, result;
Multiple variables can be created in one declaration
data type variable name
© 2004 Pearson Addison-Wesley. All rights reserved 2-13
Variable Initialization
• A variable can be given an initial value in the
declaration
• When a variable is referenced in a program, its
current value is used
• See PianoKeys.java (page 70)
int sum = 0;
int base = 32, max = 149;
© 2004 Pearson Addison-Wesley. All rights reserved 2-14
Assignment
• An assignment statement changes the value of a
variable
• The assignment operator is the = sign
total = 55;
• The value that was in total is overwritten
• You can only assign a value to a variable that is
consistent with the variable's declared type
• See Geometry.java (page 71)
• The expression on the right is evaluated and the
result is stored in the variable on the left
© 2004 Pearson Addison-Wesley. All rights reserved 2-15
Constants
• A constant is an identifier that is similar to a
variable except that it holds the same value during
its entire existence
• As the name implies, it is constant, not variable
• The compiler will issue an error if you try to
change the value of a constant
• In Java, we use the final modifier to declare a
constant
final int MIN_HEIGHT = 69;
© 2004 Pearson Addison-Wesley. All rights reserved 2-16
Constants
• Constants are useful for three important reasons
• First, they give meaning to otherwise unclear
literal values
 For example, MAX_LOAD means more than the literal 250
• Second, they facilitate program maintenance
 If a constant is used in multiple places, its value need
only be updated in one place
• Third, they formally establish that a value should
not change, avoiding inadvertent errors by other
programmers
© 2004 Pearson Addison-Wesley. All rights reserved 2-17
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Graphics
Applets
Drawing Shapes
© 2004 Pearson Addison-Wesley. All rights reserved 2-18
Primitive Data
• There are eight primitive data types in Java
• Four of them represent integers:
 byte, short, int, long
• Two of them represent floating point numbers:
 float, double
• One of them represents characters:
 char
• And one of them represents boolean values:
 boolean
© 2004 Pearson Addison-Wesley. All rights reserved 2-19
Numeric Primitive Data
• The difference between the various numeric
primitive types is their size, and therefore the
values they can store:
• We will tend to use int and double
Type
byte
short
int
long
float
double
Storage
8 bits
16 bits
32 bits
64 bits
32 bits
64 bits
Min Value
-128
-32,768
-2,147,483,648
< -9 x 1018
+/- 3.4 x 1038
with 7 significant digit
+/- 1.7 x 10308
with 15 significant dig
Max Value
127
32,767
2,147,483,647
> 9 x 1018
© 2004 Pearson Addison-Wesley. All rights reserved 2-20
Characters
• A char variable stores a single character
• Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' 'n'
• Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
• Note the distinction between a primitive character variable,
which holds only one character, and a String object, which
can hold multiple characters
© 2004 Pearson Addison-Wesley. All rights reserved 2-21
Character Sets
• A character set is an ordered list of characters,
with each character corresponding to a unique
number
• A char variable in Java can store any character
from the Unicode character set
• The Unicode character set uses sixteen bits per
character, allowing for 65,536 unique characters
• It is an international character set, containing
symbols and characters from many world
languages
© 2004 Pearson Addison-Wesley. All rights reserved 2-22
Boolean
• A boolean value represents a true or false
condition
• The reserved words true and false are the
only valid values for a boolean type
boolean done = false;
• A boolean variable can also be used to represent
any two states, such as a light bulb being on or off
© 2004 Pearson Addison-Wesley. All rights reserved 2-23
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Graphics
Applets
Drawing Shapes
© 2004 Pearson Addison-Wesley. All rights reserved 2-24
Expressions
• An expression is a combination of one or more
operators and operands which produces a result
• Arithmetic expressions compute numeric results
and make use of the arithmetic operators:
• If either or both operands used by an arithmetic
operator are floating point, then the result is a
floating point
Addition
Subtraction
Multiplication
Division
Remainder
+
-
*
/
%
© 2004 Pearson Addison-Wesley. All rights reserved 2-25
Division and Remainder
• If both operands to the division operator (/) are
integers, the result is an integer (the fractional part
is discarded)
• The remainder operator (%) returns the remainder
after dividing the second operand into the first
14 / 3 equals
8 / 12 equals
4
0
14 % 3 equals
8 % 12 equals
2
8
© 2004 Pearson Addison-Wesley. All rights reserved 2-26
Operator Precedence
• Operators can be combined into complex
expressions
result = total + count / max - offset;
• Operators have a well-defined precedence which
determines the order in which they are evaluated
• Multiplication, division, and remainder are
evaluated prior to addition, subtraction, and string
concatenation
• Arithmetic operators with the same precedence
are evaluated from left to right, but parentheses
can be used to force the evaluation order
© 2004 Pearson Addison-Wesley. All rights reserved 2-27
Operator Precedence
• What is the order of evaluation in the following
expressions?
a + b + c + d + e
1 432
a + b * c - d / e
3 241
a / (b + c) - d % e
2 341
a / (b * (c + (d - e)))
4 123
© 2004 Pearson Addison-Wesley. All rights reserved 2-28
Assignment Revisited
• The assignment operator has a lower precedence
than the arithmetic operators
First the expression on the right hand
side of the = operator is evaluated
Then the result is stored in the
variable on the left hand side
answer = sum / 4 + MAX * lowest;
14 3 2
© 2004 Pearson Addison-Wesley. All rights reserved 2-29
Assignment Revisited
• The right and left hand sides of an assignment
statement can contain the same variable
First, one is added to the
original value of count
Then the result is stored back into count
(overwriting the original value)
count = count + 1;
© 2004 Pearson Addison-Wesley. All rights reserved 2-30
Increment and Decrement
• The increment and decrement operators use only
one operand
• The increment operator (++) adds one to its
operand
• The decrement operator (--) subtracts one from
its operand
• The statement
count++;
is functionally equivalent to
count = count + 1;
© 2004 Pearson Addison-Wesley. All rights reserved 2-31
Assignment Operators
• Often we perform an operation on a variable, and
then store the result back into that variable
• Java provides assignment operators to simplify
that process
• For example, the statement
num += count;
is equivalent to
num = num + count;
© 2004 Pearson Addison-Wesley. All rights reserved 2-32
Assignment Operators
• There are many assignment operators in Java,
including the following:
Operato
r
+=
-=
*=
/=
%=
Example
x += y
x -= y
x *= y
x /= y
x %= y
Equivalent
To
x = x + y
x = x - y
x = x * y
x = x / y
x = x % y
© 2004 Pearson Addison-Wesley. All rights reserved 2-33
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Graphics
Applets
Drawing Shapes
© 2004 Pearson Addison-Wesley. All rights reserved 2-34
Data Conversion
• Sometimes it is convenient to convert data from
one type to another
• For example, in a particular situation we may want
to treat an integer as a floating point value
• These conversions do not change the type of a
variable or the value that's stored in it – they only
convert a value as part of a computation
© 2004 Pearson Addison-Wesley. All rights reserved 2-35
Data Conversion
• Conversions must be handled carefully to avoid
losing information
• Widening conversions are safest because they
tend to go from a small data type to a larger one
(such as a short to an int)
• Narrowing conversions can lose information
because they tend to go from a large data type to a
smaller one (such as an int to a short)
• In Java, data conversions can occur in three ways:
 assignment conversion
 promotion
 casting
© 2004 Pearson Addison-Wesley. All rights reserved 2-36
Assignment Conversion
• Assignment conversion occurs when a value of
one type is assigned to a variable of another
• If money is a float variable and dollars is an
int variable, the following assignment converts
the value in dollars to a float
money = dollars;
• Only widening conversions can happen via
assignment
• Note that the value or type of dollars did not
change
© 2004 Pearson Addison-Wesley. All rights reserved 2-37
Data Promotion
• Promotion happens automatically when operators
in expressions convert their operands
• For example, if sum is a float and count is an
int, the value of count is converted to a floating
point value to perform the following calculation:
result = sum / count;
© 2004 Pearson Addison-Wesley. All rights reserved 2-38
Casting
• Casting is the most powerful, and dangerous,
technique for conversion
• Both widening and narrowing conversions can be
accomplished by explicitly casting a value
• To cast, the type is put in parentheses in front of
the value being converted
• For example, if total and count are integers, but
we want a floating point result when dividing them,
we can cast total:
result = (float) total / count;
© 2004 Pearson Addison-Wesley. All rights reserved 2-39
Summary
• Week 2 focused on:
 character strings
 primitive data
 the declaration and use of variables
 expressions and operator precedence
 data conversions

More Related Content

What's hot

Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Cso gaddis java_chapter13
Cso gaddis java_chapter13Cso gaddis java_chapter13
Cso gaddis java_chapter13mlrbrown
 
Sv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmSv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmHARINATH REDDY
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_conceptAmit Gupta
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & StreamsC4Media
 
Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014Simon Ritter
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6dplunkett
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Raj Naik
 
Comp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source codeComp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source codepradesigali1
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3dplunkett
 
Using Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUUsing Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUSkills Matter
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7dplunkett
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5dplunkett
 
03 expressions.ppt
03 expressions.ppt03 expressions.ppt
03 expressions.pptBusiness man
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01Zafor Iqbal
 

What's hot (20)

Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Cso gaddis java_chapter13
Cso gaddis java_chapter13Cso gaddis java_chapter13
Cso gaddis java_chapter13
 
Sv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmSv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvm
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_concept
 
Arrays in c_language
Arrays in c_language Arrays in c_language
Arrays in c_language
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
Comp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source codeComp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source code
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
Using Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUUsing Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPU
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
 
03 expressions.ppt
03 expressions.ppt03 expressions.ppt
03 expressions.ppt
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 

Viewers also liked

Installing and setting up eclipse java projects
Installing and setting up eclipse java projectsInstalling and setting up eclipse java projects
Installing and setting up eclipse java projectshccit
 
Assessments
AssessmentsAssessments
Assessmentshccit
 
Week11
Week11Week11
Week11hccit
 
Jg chap3
Jg chap3Jg chap3
Jg chap3hccit
 
Jg contents chap1
Jg contents chap1Jg contents chap1
Jg contents chap1hccit
 
Week03
Week03Week03
Week03hccit
 
Notes2
Notes2Notes2
Notes2hccit
 
Meteorologistas BritâNicos Identificam Novo Tipo De Nuvem
Meteorologistas BritâNicos Identificam Novo Tipo De NuvemMeteorologistas BritâNicos Identificam Novo Tipo De Nuvem
Meteorologistas BritâNicos Identificam Novo Tipo De Nuvem Luciano Alencar
 
Pauta Iv Encontro
Pauta Iv EncontroPauta Iv Encontro
Pauta Iv EncontroMDLSOUZA
 
Jeopardy review chapter 1
Jeopardy review   chapter 1Jeopardy review   chapter 1
Jeopardy review chapter 1dhornbeck
 
Réunion Intergroupe MR : La confiance à Didier Reynders
Réunion Intergroupe MR : La confiance à Didier ReyndersRéunion Intergroupe MR : La confiance à Didier Reynders
Réunion Intergroupe MR : La confiance à Didier ReyndersMichel Péters
 
Pauta I Encontro
Pauta I EncontroPauta I Encontro
Pauta I EncontroMDLSOUZA
 
Chapter 1 section 2 notes
Chapter 1 section 2 notesChapter 1 section 2 notes
Chapter 1 section 2 notesdhornbeck
 
Law-Exchange.co.uk Shared Resource
Law-Exchange.co.uk Shared ResourceLaw-Exchange.co.uk Shared Resource
Law-Exchange.co.uk Shared Resourcelawexchange.co.uk
 
Go Plant Based by Green Yatra
Go Plant Based by Green YatraGo Plant Based by Green Yatra
Go Plant Based by Green YatraGreen Yatra
 
Digitizing your Business Model
Digitizing your Business Model Digitizing your Business Model
Digitizing your Business Model Beatriz Briones
 
Itinerario 1ra
Itinerario 1raItinerario 1ra
Itinerario 1raBaloncesto
 

Viewers also liked (20)

Installing and setting up eclipse java projects
Installing and setting up eclipse java projectsInstalling and setting up eclipse java projects
Installing and setting up eclipse java projects
 
Assessments
AssessmentsAssessments
Assessments
 
Week11
Week11Week11
Week11
 
Jg chap3
Jg chap3Jg chap3
Jg chap3
 
Jg contents chap1
Jg contents chap1Jg contents chap1
Jg contents chap1
 
Week03
Week03Week03
Week03
 
Notes2
Notes2Notes2
Notes2
 
Meteorologistas BritâNicos Identificam Novo Tipo De Nuvem
Meteorologistas BritâNicos Identificam Novo Tipo De NuvemMeteorologistas BritâNicos Identificam Novo Tipo De Nuvem
Meteorologistas BritâNicos Identificam Novo Tipo De Nuvem
 
Pauta Iv Encontro
Pauta Iv EncontroPauta Iv Encontro
Pauta Iv Encontro
 
Jeopardy review chapter 1
Jeopardy review   chapter 1Jeopardy review   chapter 1
Jeopardy review chapter 1
 
Réunion Intergroupe MR : La confiance à Didier Reynders
Réunion Intergroupe MR : La confiance à Didier ReyndersRéunion Intergroupe MR : La confiance à Didier Reynders
Réunion Intergroupe MR : La confiance à Didier Reynders
 
Pauta I Encontro
Pauta I EncontroPauta I Encontro
Pauta I Encontro
 
Chapter 1 section 2 notes
Chapter 1 section 2 notesChapter 1 section 2 notes
Chapter 1 section 2 notes
 
Esquema
EsquemaEsquema
Esquema
 
Law-Exchange.co.uk Shared Resource
Law-Exchange.co.uk Shared ResourceLaw-Exchange.co.uk Shared Resource
Law-Exchange.co.uk Shared Resource
 
Go Plant Based by Green Yatra
Go Plant Based by Green YatraGo Plant Based by Green Yatra
Go Plant Based by Green Yatra
 
Digitizing your Business Model
Digitizing your Business Model Digitizing your Business Model
Digitizing your Business Model
 
Bob marley vol 2
Bob marley vol 2Bob marley vol 2
Bob marley vol 2
 
Aviation Panel1
Aviation Panel1Aviation Panel1
Aviation Panel1
 
Itinerario 1ra
Itinerario 1raItinerario 1ra
Itinerario 1ra
 

Similar to Week02

Week05
Week05Week05
Week05hccit
 
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptxdoopagamer
 
Object oriented programming 9 expressions and type casting in c++
Object oriented programming 9 expressions and type casting in c++Object oriented programming 9 expressions and type casting in c++
Object oriented programming 9 expressions and type casting in c++Vaibhav Khanna
 
Learning core java
Learning core javaLearning core java
Learning core javaAbhay Bharti
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 
CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)Dilawar Khan
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of CSuchit Patel
 
C Programming : Pointers and Strings
C Programming : Pointers and StringsC Programming : Pointers and Strings
C Programming : Pointers and StringsSelvaraj Seerangan
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Simon Ritter
 
Introduction to c
Introduction to cIntroduction to c
Introduction to cAjeet Kumar
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 

Similar to Week02 (20)

Week05
Week05Week05
Week05
 
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptx
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Object oriented programming 9 expressions and type casting in c++
Object oriented programming 9 expressions and type casting in c++Object oriented programming 9 expressions and type casting in c++
Object oriented programming 9 expressions and type casting in c++
 
Learning core java
Learning core javaLearning core java
Learning core java
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Java chapter 2
Java chapter 2Java chapter 2
Java chapter 2
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
Aspdot
AspdotAspdot
Aspdot
 
CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
PHP
PHPPHP
PHP
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
C Programming : Pointers and Strings
C Programming : Pointers and StringsC Programming : Pointers and Strings
C Programming : Pointers and Strings
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
PPT 19.pptx
PPT 19.pptxPPT 19.pptx
PPT 19.pptx
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 

More from hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12hccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs emailhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 

More from hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 

Recently uploaded

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Week02

  • 2. © 2004 Pearson Addison-Wesley. All rights reserved 2-2 Data and Expressions • Let's explore some other fundamental programming concepts • Chapter 2 focuses on:  character strings  primitive data  the declaration and use of variables  expressions and operator precedence  data conversions  accepting input from the user
  • 3. © 2004 Pearson Addison-Wesley. All rights reserved 2-3 Copyright Warning COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice.
  • 4. © 2004 Pearson Addison-Wesley. All rights reserved 2-4 Character Strings • A string of characters can be represented as a string literal by putting double quotes around the text: • Examples: "This is a string literal." "123 Main Street" "X" • Every character string is an object in Java, defined by the String class • Every string literal represents a String object
  • 5. © 2004 Pearson Addison-Wesley. All rights reserved 2-5 The println Method • In the Lincoln program from Chapter 1, we invoked the println method to print a character string • The System.out object represents a destination (the monitor screen) to which we can send output System.out.println ("Whatever you are, be a good one."); objec t method name information provided to the method (parameters)
  • 6. © 2004 Pearson Addison-Wesley. All rights reserved 2-6 The print() Method • The System.out object provides another service as well • The print method is similar to the println method, except that it does not advance to the next line • Therefore anything printed after a print statement will appear on the same line • See Countdown.java (page 63)
  • 7. © 2004 Pearson Addison-Wesley. All rights reserved 2-7 String Concatenation • The string concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly" • It can also be used to append a number to a string • A string literal cannot be broken across two lines in a program • See Facts.java (page 65)
  • 8. © 2004 Pearson Addison-Wesley. All rights reserved 2-8 String Concatenation • The + operator is also used for arithmetic addition • The function that it performs depends on the type of the information on which it operates • If both operands are strings, or if one is a string and one is a number, it performs string concatenation • If both operands are numeric, it adds them • The + operator is evaluated left to right, but parentheses can be used to force the order • See Addition.java (page 67)
  • 9. © 2004 Pearson Addison-Wesley. All rights reserved 2-9 Escape Sequences • What if we wanted to print the quote character? • The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); • An escape sequence is a series of characters that represents a special character • An escape sequence begins with a backslash character () System.out.println ("I said "Hello" to you.");
  • 10. © 2004 Pearson Addison-Wesley. All rights reserved 2-10 Escape Sequences • Some Java escape sequences: • See Roses.java (page 68) Escape Sequence b t n r " ' Meaning backspace tab newline carriage return double quote single quote backslash
  • 11. © 2004 Pearson Addison-Wesley. All rights reserved 2-11 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes
  • 12. © 2004 Pearson Addison-Wesley. All rights reserved 2-12 Variables • A variable is a name for a location in memory • A variable must be declared by specifying the variable's name and the type of information that it will hold int total; int count, temp, result; Multiple variables can be created in one declaration data type variable name
  • 13. © 2004 Pearson Addison-Wesley. All rights reserved 2-13 Variable Initialization • A variable can be given an initial value in the declaration • When a variable is referenced in a program, its current value is used • See PianoKeys.java (page 70) int sum = 0; int base = 32, max = 149;
  • 14. © 2004 Pearson Addison-Wesley. All rights reserved 2-14 Assignment • An assignment statement changes the value of a variable • The assignment operator is the = sign total = 55; • The value that was in total is overwritten • You can only assign a value to a variable that is consistent with the variable's declared type • See Geometry.java (page 71) • The expression on the right is evaluated and the result is stored in the variable on the left
  • 15. © 2004 Pearson Addison-Wesley. All rights reserved 2-15 Constants • A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence • As the name implies, it is constant, not variable • The compiler will issue an error if you try to change the value of a constant • In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69;
  • 16. © 2004 Pearson Addison-Wesley. All rights reserved 2-16 Constants • Constants are useful for three important reasons • First, they give meaning to otherwise unclear literal values  For example, MAX_LOAD means more than the literal 250 • Second, they facilitate program maintenance  If a constant is used in multiple places, its value need only be updated in one place • Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers
  • 17. © 2004 Pearson Addison-Wesley. All rights reserved 2-17 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes
  • 18. © 2004 Pearson Addison-Wesley. All rights reserved 2-18 Primitive Data • There are eight primitive data types in Java • Four of them represent integers:  byte, short, int, long • Two of them represent floating point numbers:  float, double • One of them represents characters:  char • And one of them represents boolean values:  boolean
  • 19. © 2004 Pearson Addison-Wesley. All rights reserved 2-19 Numeric Primitive Data • The difference between the various numeric primitive types is their size, and therefore the values they can store: • We will tend to use int and double Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digit +/- 1.7 x 10308 with 15 significant dig Max Value 127 32,767 2,147,483,647 > 9 x 1018
  • 20. © 2004 Pearson Addison-Wesley. All rights reserved 2-20 Characters • A char variable stores a single character • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' 'n' • Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; • Note the distinction between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters
  • 21. © 2004 Pearson Addison-Wesley. All rights reserved 2-21 Character Sets • A character set is an ordered list of characters, with each character corresponding to a unique number • A char variable in Java can store any character from the Unicode character set • The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages
  • 22. © 2004 Pearson Addison-Wesley. All rights reserved 2-22 Boolean • A boolean value represents a true or false condition • The reserved words true and false are the only valid values for a boolean type boolean done = false; • A boolean variable can also be used to represent any two states, such as a light bulb being on or off
  • 23. © 2004 Pearson Addison-Wesley. All rights reserved 2-23 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes
  • 24. © 2004 Pearson Addison-Wesley. All rights reserved 2-24 Expressions • An expression is a combination of one or more operators and operands which produces a result • Arithmetic expressions compute numeric results and make use of the arithmetic operators: • If either or both operands used by an arithmetic operator are floating point, then the result is a floating point Addition Subtraction Multiplication Division Remainder + - * / %
  • 25. © 2004 Pearson Addison-Wesley. All rights reserved 2-25 Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) • The remainder operator (%) returns the remainder after dividing the second operand into the first 14 / 3 equals 8 / 12 equals 4 0 14 % 3 equals 8 % 12 equals 2 8
  • 26. © 2004 Pearson Addison-Wesley. All rights reserved 2-26 Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order
  • 27. © 2004 Pearson Addison-Wesley. All rights reserved 2-27 Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e 1 432 a + b * c - d / e 3 241 a / (b + c) - d % e 2 341 a / (b * (c + (d - e))) 4 123
  • 28. © 2004 Pearson Addison-Wesley. All rights reserved 2-28 Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated Then the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest; 14 3 2
  • 29. © 2004 Pearson Addison-Wesley. All rights reserved 2-29 Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count Then the result is stored back into count (overwriting the original value) count = count + 1;
  • 30. © 2004 Pearson Addison-Wesley. All rights reserved 2-30 Increment and Decrement • The increment and decrement operators use only one operand • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++; is functionally equivalent to count = count + 1;
  • 31. © 2004 Pearson Addison-Wesley. All rights reserved 2-31 Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process • For example, the statement num += count; is equivalent to num = num + count;
  • 32. © 2004 Pearson Addison-Wesley. All rights reserved 2-32 Assignment Operators • There are many assignment operators in Java, including the following: Operato r += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y
  • 33. © 2004 Pearson Addison-Wesley. All rights reserved 2-33 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes
  • 34. © 2004 Pearson Addison-Wesley. All rights reserved 2-34 Data Conversion • Sometimes it is convenient to convert data from one type to another • For example, in a particular situation we may want to treat an integer as a floating point value • These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation
  • 35. © 2004 Pearson Addison-Wesley. All rights reserved 2-35 Data Conversion • Conversions must be handled carefully to avoid losing information • Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) • In Java, data conversions can occur in three ways:  assignment conversion  promotion  casting
  • 36. © 2004 Pearson Addison-Wesley. All rights reserved 2-36 Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another • If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float money = dollars; • Only widening conversions can happen via assignment • Note that the value or type of dollars did not change
  • 37. © 2004 Pearson Addison-Wesley. All rights reserved 2-37 Data Promotion • Promotion happens automatically when operators in expressions convert their operands • For example, if sum is a float and count is an int, the value of count is converted to a floating point value to perform the following calculation: result = sum / count;
  • 38. © 2004 Pearson Addison-Wesley. All rights reserved 2-38 Casting • Casting is the most powerful, and dangerous, technique for conversion • Both widening and narrowing conversions can be accomplished by explicitly casting a value • To cast, the type is put in parentheses in front of the value being converted • For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count;
  • 39. © 2004 Pearson Addison-Wesley. All rights reserved 2-39 Summary • Week 2 focused on:  character strings  primitive data  the declaration and use of variables  expressions and operator precedence  data conversions