Title: Java : Primitive Data Types, Operators and Control
1Java Primitive Data Types, Operators and
Control
September 17, 2007
2Things to Ignore (for now)
- In Chapter 2 of Raposa, be aware of but dont
worry about - Bitwise operators
- Shift operators
3What is Java?
- Java
- Compiled language
- Executes within a virtual machine
- This is what makes it highly portable
- Is C like in terms of syntax and simple control
constructs - Is purely object-oriented
- Is a strongly typed language
4The basics of the Java
- Rules for identifiers
- The first character must be an underscore, upper-
or lower-case letter, or a dollar sign - Java is case sensitive
- Subsequent characters may be any upper- or
lower-case letter, digit, underscore or a dollar
sign - Cannot be a keyword, true, false or null
- Recommendation!
- Do not use dollar signs
- Dollar signs are typically intended for use by
code generation tools
5Reserved Words
- Java has, like, 50 keywords
- Get to know them
- Interesting trivia
- const and goto are keywords
- They have no implementation in Java
- They do cause compilation errors
6Built-in Types
- There are eight built-in types
- Java calls the primitive types
-27 to 27-1
-215 to 215-1 -231 to 231-1 -263 to 263-1
(/-)1.410-45 to 3.41038 (/-)4.910-324
to 1.810308
7Literals
8Quick!
- What would System.out.println(x) produce?
- int x 45
- int x 045
- int x 0x45
9Constants
- Java calls constants final
- Java has blank finals
- Have no initial value
- Are fixed upon first assignment
Syntax for declaration constants final int x
7 //x is fixed to the value 7 x 2
//compilation error final int y //blank
final y 3 //y is now fixed at 3 y
7 //compiler error
10Declaring Variables, Assigning Values and
Comparisons
- Java is typed
- Variables must include a type
- May include an initial value
- Assignment
- Comparison
Syntax for declaration, assignment and
comparison int x ? declare that x is a
variable x 5 ? assign x the value 5 x 7 ?
compare value of x to 7
11Operators
- Java has numerous built-in operators
- Operators mostly apply only to the primitive
types - There are exceptions which we will point out
- Most operators apply to all primitive data types
- There are exceptions which we will point out
12Assignment Operator
- Used to assign the value on the right to the
value on the left - For primitive data types, this works as expected
- For all other Java objects, we need further
discussion
13Objects vs. References
- Identifiers of primitive data types represent
objects
memory
int i
ltintegergt
When this line is executed, space is allocated to
store i. Where i is stored, an integer lives
14Objects vs. References
- Identifiers of classes represent references
memory
String s
ltaddressgt
When this line is executed, space is allocated to
store s. Where s is stored, lives the address of
where the string is located.
String
15Objects vs. References
- Assignment copies what is stored where an
identifier lives
int i 5int j 7i j
String s new String(Fred)String t new
String(Ethel)s t
After the last line executes, both i and j have
the same value.
After the last line executes, both s and t store
the same address.
16Relational Operator
!
- Used to test if the value on the left is equal to
the value on the right - For primitive data types, this works as expected
- For all other Java objects, this only test
addresses, not referenced values!
17Example String
String s new String(Fred)String t new
String(Fred)System.out.println(s t)s
tSystem.out.println(s t)
Prints false. The address of s and t are not
the same.
Prints true. The address of s and t are the
same.
18Example String
String s FredString t FredSystem.out
.println(s t)
What gets printed?
Why?
19Relational Operators
- Other relational operators for primitive types
lt lt gt gt
- These do not apply to
- Boolean
- Any class-based objects
20Mathematical Operators
- Standard math operators (apply to all primitives
but boolean)
- / - (unary) (unary)
- Short-cut math operators (apply to all primitives
but boolean)
-- - /
21Logical Operators
- Logical operators apply only to boolean values
( short-circuit and) (and)
(short-circuit or) (or) (exclusive
or)! (not)
22Short Circuiting
- Care must be taken with compound logical
statements - Java uses short-circuiting
- Statements are evaluated only as far as they need
to be to determine the value
23Example Short Circuit
g() is called only if f() returns false. h() is
called only if g() and f() return false.
boolean f()boolean g()boolean h()if (
f() g() h() ) . . .if ( f() g()
h() )
g() is called only if f() returns true. h() is
called only if g() and f() return true.
24Example - Bitwise
f(), g() and h() are all invoked and then the
expression is evaluated
boolean f()boolean g()boolean h()if (
f() g() h() ) . . .if ( f() g() h()
)
25Casting
- Objects can and may need to be converted from one
type to another - This is called casting
int i 5double d 4.2i di (int)
d
Generates a syntax error. Loss of precision will
occur
We need to explicitly convert since there is loss
of precision.
26Promotion
- In certain circumstances, the Java will cast for
us - When there is no chance of loss of information
- This is called promotion
int i 5double d 4.2d i
Going from int to double is represents no loss of
precision. Java converts automatically.
27Execution Control
if if-else if-else ifwhiledo-whilefor
switch
28if statement
- Provides a decision point
Syntax
Example
if (divisor 0) System.out.println
(Error Division by zero!)
if (boolean-exp) statements
29if-else statement
- Provides a decision with alternative
Syntax
Example
if (divisor ! 0) quotient value /
divisor else System.out.println
(Error Division by zero!)
if (boolean-exp) statements else
statements
30if-else if statement
- Provides a set of decisions with multiple
alternatives
Syntax
Example
if (status DNE) System. out.println
(Error File does not exist!) else if
(status ERROR) System.out.println
(Error Cant open file!)
if (boolean-exp) statements else if
(boolean-exp) statements
31if-else if - else statement
- Provides a set of decisions with multiple
alternatives and a default alternative
Syntax
Example
if (n lt 0) System.out.println (n is
negative) else if (n gt 0)
System.out.println (n is positive)
else System.out.println (n is
zero)
if (boolean-exp) statements else if
(boolean-exp) statements else
statements
32Be Careful!
- Compound if statements are evaluated in the order
they are specified
Incorrect
Correct
if (n gt 0) System.out.println (n
has 1 digit) else if (n gt 10)
System.out.println (n has 2 digits)
else if (n gt 100) System.out.println
(n has 3 digits)
if (n gt 100) System.out.println (n
has 3 digits) else if (n gt 10)
System.out.println (n has 2 digits)
else if (n gt 0) System.out.println
(n has 1 digit)
33Returning from a statement
- If statements are often used in operations to
decide a return value
// Operation splits the string into two strings
at the position // indicated. The following must
be true // // 0 lt pos lt length-2 //
public String split(String s, int pos)
String result (null, null) if ( (pos
lt 0) (pos gt s.length()-2))
System.out.println(Error Bad value for pos!)
return result result0
s.substring(0,pos) result1
s.substring(pos) return result
If pos was not specified correctly, the operation
would return without executing the splitting
statements
34Good Practice
- Have only 1 point of return
// Operation splits the string into two strings
at the position // indicated. The following must
be true // // 0 lt pos lt length-2 //
public String split(String s, int pos)
String result (null, null) if ( (pos
lt 0) (pos gt s.length()-2))
System.out.println(Error Bad value for pos!)
else result0
s.substring(0,pos) result1
s.substring(pos) return result
This makes the operation easier to follow. There
is only one way to leave the opertion. This is
especially useful when writing complex operations.
35while loops
- Enables a sequence of statements to be iterated
while a given condition is true - Condition is checked before entering loop
Syntax
while (boolean-exp) statements
Example
char response while ( !( (response
Y) (response N) ) ) response
getResponse()
36do-while loops
- Like while, enables a sequence of statements to
be iterated while a given condition is true - Condition is checked after entering loop
Syntax
do statements while (boolean-exp)
Example
char response do response
getResponse() while ( !( (response Y)
(response N) ) )
37while vs. do-while
- Statements are similar but
- while loops may never execute the statements
inside the loop - do-while loops execute the statements inside the
loop at least once
do-while
while
do statements while (boolean-exp)
while (boolean-exp) statements
Condition is checked at the top of the loop. If
the condition initially is false, the loop
doesnt execute.
Condition is checked at the bottom of the loop.
The loop executes at least once before checking
condition.
38for loops
- Use a for loop when you need to do something a
set number of times
Syntax
for (initialization boolean-exp step)
statements
Example
for (int n2 nlt100 n) if (isPrime(n))
System.out.println(n is prime!)
39for loops
- Think of the parameters as follows
Syntax
for (initialization boolean-exp step)
statements
initialization Where do I start?boolean-exp
When do I continue?step How do I
progress?
40for loops
Syntax
for (initialization boolean-exp step)
statements
- Perform initialization
- If boolean-exp is true, execute statements in
loop - Perform the step instructions
- Goto 2
41for loops
- Parameters could be operations
Example
for (initialize() seeIfDone() getNext())
statements
42for loops
- There are more exotic forms
- Dont worry about for the time being
43Loops and returning
- It is possible to return from within a loop
- It is not a good practice
- Defeats the purpose of the loop
Bad practice
Good practice
for (int i0 ilts.length() i) if
(letterToFind s.charAt(i)) return
true return false
result false for (int i0 ilts.length() i)
if (letterToFind s.charAt(i))
result true return result
44Breaking
- It is also possible to break out of a loop
without returning - Again, this is typically a bad practice
Bad practice
Good practice
result false for (int i0 ilts.length() i)
if (letterToFind s.charAt(i))
result true break return false
result false for (int i0 ilts.length() i)
if (letterToFind s.charAt(i))
result true return result
45Continuing
- We can also can also force the next iteration of
a loop - Similar to breaking, use of the continue should
be avoided when possible
Bad practice
Better practice
for (int i3 ilt99 i) if (i3 ! 0)
continue System.out.println(i)
for (int i3 ilt99 i3)
System.out.println(i)
46switch statements
- Provides a selection based on an integral value
Syntax
Example
switch (charFromInput) case Y case
y start() break case N
case n stop() break
default System.out.println
(Invalid response!) break
switch (integral-selector) case
integral-value statements
break case integral-value case
integral-value case integral-value
statements break default
statements break
47Two Java Quirks
- String
- Arrays
- We will understand these later