Arrays Jiafan Zhou. 2 Background Programmer often need the ability to represent a group of values...
141
Arrays Jiafan Zhou
Arrays Jiafan Zhou. 2 Background Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional
2 Background Programmer often need the ability to represent a
group of values as a list List may be one-dimensional or
multidimensional Java provides arrays and the collection classes
The Vector class is an example of a collection class Consider
arrays first
Slide 3
3 Example Definitions char[] c; int[] value = new int[10];
Causes Array object variable c is un-initialized Array object
variable value references a new ten element list of integers Each
of the integers is default initialized to 0 value 0 0000 -c
Slide 4
4 An array example int[] v = new int[10]; int i = 7; int j = 2;
int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] +
v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] =
stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k
= 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0];
v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt();
int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1;
v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12;
System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new
int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j]
= v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12;
System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new
int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j]
= v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12;
System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new
int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j]
= v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12;
System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new
int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j]
= v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12;
System.out.println(v[2]); v[k] = stdin.nextInt(); 8 is displayed
int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1;
v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12;
System.out.println(v[2]); v[k] = stdin.nextInt(); Suppose 3 is
extracted int[] v = new int[10]; int i = 7; int j = 2; int k = 4;
v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]]
= 12; System.out.println(v[2]); v[k] = stdin.nextInt();
Slide 5
5 Array variable definition styles Without initialization Type
of values in list Name of list Brackets indicate array variable
being defined ElementType [ ] id; int [] a; int a[];
Slide 6
6 Array variable definition styles With initialization
ElementType [] id = new ElementType [n]; Nonnegative integer
expression specifying the number of elements in the array A new
array of n elements
Slide 7
7 Where weve seen arrays public static void main (String[]
args) Thus, the main() method takes in a String array as the
parameter Note that you can also define it as: public static void
main (String args[]) or public static void main (String[]
foobar)
Slide 8
8 Basic terminology List is composed of elements Elements in a
list have a common name Example: a[3] = 5; The common name is a The
list as a whole is referenced through the common name List elements
are of the same type the base type Elements of a list are
referenced by subscripting (indexing) the common name
Slide 9
9 Java array features Subscripts are denoted as expressions
within brackets: [ ] Base (element) type can be any type Size of
array can be specified at run time This is different that pure C!
(for the most part, at least) Index type is integer and the index
range must be 0... n-1 Where n is the number of elements Just like
Strings indexing! Automatic bounds checking Ensures any reference
to an array element is valid Data field length specifies the number
of elements in the list Array is an object Has features common to
all other objects More on this later
Slide 10
10 Review of arrays Creating an array: int[] foo = new int[10];
Accessing an array: foo[3] = 7; System.out.print (foo[1]); Creating
an array: String[] bar = new String[10]; Accessing an array: bar[3]
= qux; System.out.println (bar[1]);
Slide 11
11 Consider Segment int[] b = new int[100]; b[-1] = 0; b[100] =
0; Causes Array variable to reference a new list of 100 integers
Each element is initialized to 0 Two exceptions to be thrown -1 is
not a valid index too small 100 is not a valid index too large
IndexOutOfBoundsException
Slide 12
12 Consider Point[] p = new Point[3]; p[0] = new Point(0, 0);
p[1] = new Point(1, 1); p[2] = new Point(2, 2); p[0].setX(1);
p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0];
p[2] = vertex; p p[0]p[1]p[2] null Point: (0, 0) p p[0]p[1] Point:
(1, 1)Point: (2, 2) p[2] Point: (1, 0) p p[0]p[1] Point: (1,
1)Point: (2, 2) p[2] Point: (1, 0) p p[0]p[1] Point: (1, 2)Point:
(2, 2) p[2] Point: (1, 0) p p[0]p[1] Point: (1, 2)Point: (2, 2)
p[2] vertex Point: (4, 4) Point: (1, 0) p p[0]p[1] Point: (2, 2)
p[2] vertex Point: (4, 4) Point: (1, 0) p p[0]p[1]p[2] vertex
Point: (4, 4) Point[] p = new Point[3]; p[0] = new Point(0, 0);
p[1] = new Point(1, 1); p[2] = new Point(2, 2); p[0].setX(1);
p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0];
p[2] = vertex;
Slide 13
13 Explicit initialization Syntax ElementType [] id = { exp 0,
1,... exp n }; id references an array of n elements. id[0] has
value exp 0, id[1] has value exp 1, and so on. Each exp i is an
expression that evaluates to type ElementType
Slide 14
14 Explicit initialization Example String[] puppy = { pika,
mila, arlo, nikki }; int[] unit = { 1 }; Equivalent to String[]
puppy = new String[4]; puppy[0] = pika"; puppy[1] = mila"; puppy[2]
= arlo"; puppy[3] = nikki"; int[] unit = new int[1]; unit[0] =
1;
Slide 15
15 Array members Member length Size of the array for (int i =
0; i < puppy.length; ++i) { System.out.println(puppy[i]); } Note
that length is a field, not a method! I.e., it is not
puppy.length()
Slide 16
16 Array members Member clone() Produces a shallow copy Point[]
u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone();
v[1] = new Point(4, 30); Point: (0, 0)Point: (1, 1) u u[0]u[1]
Point: (0, 0) v v[0]v[1] Point: (1, 1) u u[0]u[1] Point: (0, 0) v
v[0]v[1] Point: (1, 1) u u[0]u[1] Point: (4, 30) Point[] u = { new
Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new
Point(4, 30);
Slide 17
17 Member clone() Produces a shallow copy Point[] u = { new
Point(0, 0), new Point(1, 1)}; Point[] v = u.clone();
v[1].setX(10); Point[] u = { new Point(0, 0), new Point(1, 1)};
Point[] v = u.clone(); v[1].setX(10); Array members Point: (0,
0)Point: (1, 1) u u[0]u[1] Point: (0, 0) v v[0]v[1] Point: (1, 1) u
u[0]u[1] Point: (0, 0) v v[0]v[1] Point: (10, 1) u u[0]u[1]
Slide 18
18 How Java represents arrays Consider int[] a = { 1, 2, 3, 4,
5 }; a 1 2345 + Array - length = 5 - data = 12345
Slide 19
19 More about how Java represents Arrays Consider int[] a;
int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 };
a = c; d = c; 1 23450 0000 a - b null cd int[] a; int[] b = null;
int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d =
c;
Slide 20 0 ) { for ( int i = 0; i < args.length; i++ )
System.out.println ("parameter " + i + ": '" + args[i] + "'"); } }
}">
20 Consider that main() method again public static void main
(String args[]) How does one pass in a parameter to the main
method? public class MainParameters { public static void main
(String args[]) { System.out.println ("Number of paramters to +
"main(): " + args.length); if ( args.length > 0 ) { for ( int i
= 0; i < args.length; i++ ) System.out.println ("parameter " + i
+ ": '" + args[i] + "'"); } } }
Slide 21
21 Program Demo MainParameters.java Via Eclipse Via the command
line
Slide 22
22 System.out.println("Enter search value (number): "); int key
= stdin.nextInt(); int i; for (i = 0; i < data.length; ++i) { if
(key == data[i]) { break; } } if (i != data.length) {
System.out.println(key + " is the " + i + "-th element"); } else {
System.out.println(key + " is not in the list"); } ++i
System.out.println("Enter search value (number): "); int key =
stdin.nextInt(); int i; if (key == data[i]) { break; if (i !=
data.length) { System.out.println(key + " is the " + i + "-th
element"); } i < data.length i = 0 Searching for a value
Slide 23
23 Searching for the minimum value Segment int minimumSoFar =
sample[0]; for (int i = 1; i < sample.length; ++i) { if
(sample[i] < minimumSoFar) { minimumSoFar = sample[i]; } }
Slide 24
24 Sorting Problem Arranging elements so that they are ordered
according to some desired scheme Standard is non-decreasing order
Why don't we say increasing order? Major tasks Comparisons of
elements Updates or element movement
Slide 25
25 Iteration i // find the location of the ith smallest element
int spot = i; for (int j = i+1; j < v.length; ++j) { if (v[j]
< v[spot]) // is spot ok? // update spot with index of smaller
element spot = j; } // spot is now correct, swap elements v[spot]
and v[i]
Slide 26
26 Binary search Given a list, find a specific element in the
list List MUST be sorted! Each time it iterates through, it cuts
the search space in half A binary search is MUCH faster than a
sequential search
Slide 27
27 Binary search vs. sequential search Assume the array has n
elements Sequential search takes n iterations to find the element
Binary search takes log 2 n iterations to find the element Consider
a list of 1 million elements Binary search takes about 20
iterations Sequential search takes 1,000,000 iterations Consider a
list of 1 trillion elements Binary search takes about 40 iterations
Sequential search takes 1,000,000,000,000 iterations
Slide 28
28 Limitations of arrays You cant change their size once
created This can be a big problem! So we will create a new class
that will operate like an array: We can store and get elements by
index number It will automatically increase in size as needed And
other fancy features Lets call the class Vector As we are basically
writing the java.util.Vector class
Slide 29
29 Properties of our Vector class It needs to have an array to
hold the values As our internal array will often be bigger than the
number of elements in the Vector, we need a size as well More on
what this means in a slide or two Not much else
Slide 30
30 Methods in our Vector class Insert and remove elements into
the Vector Get an element from the Vector Find the length Print it
out to the screen What happens when the array field is full, and we
want to add an element? We will need to increase the size of the
array So we need a method to do that as well
Slide 31
31 Our first take on our Vector class public class Vector {
private Object array[]; private int size = 0; Vector() { array =
new Object[100]; } Vector(int length) { array = new Object[length];
} } What does this mean? Well see that a bit later But briefly, it
means the array can store any object
Slide 32
32 Adding an element to our Vector public void add (Object o) {
array[size++] = o; } Pretty easy! But what if the array is full? We
need a way to increase the capacity of the array
Slide 33
33 Increasing the Vectors arrays capacity private void
increaseCapacity() { int oldSize = array.length; Object newArray[]
= new Object[2*oldSize]; for ( int i = 0; i < oldSize; i++ )
newArray[i] = array[i]; array = newArray; } And our new add()
method: public void add (Object o) { if ( size == array.length )
increaseCapacity(); array[size++] = o; }
Slide 34
34 Methods can be private as well Notice that the
increaseCapacity() method is called only by the add() method when
necessary Its not ever going to be called by whomever is using our
Vector Thus, we will make it private That means that only other
Vector methods can call it
Slide 35
35 Removing an element from a Vector public Object remove (int
which) { Object ret = array[which]; for ( int i = which; i <
array.length-1; i++ ) array[i] = array[i+1]; array[array.length-1]
= null; size--; return ret; }
Slide 36
36 Miscellaneous other methods public int size() { return size;
} public Object get (int which) { return array[which]; }
Slide 37
37 Our toString() method public String toString() { String ret
= "["; for ( int i = 0; i < size; i++ ) { ret += array[i]; if (
i != size-1 ) ret += ", "; } ret += "]"; return ret; }
Slide 38
38 Using our Vector This code is in a separate class called
VectorUsage public static void main (String[] args) { Vector v =
new Vector(); for ( int i = 12; i < 30; i++ ) { v.add
(String.valueOf(i)); } System.out.println (v); System.out.println
(v.size()); String s = (String) v.get(5); System.out.println (s);
v.remove (5); System.out.println (v); v.remove (5);
System.out.println (v); }
Slide 39
39 The real Vector class Java provides a Vector class In
java.util It contains all of the methods shown
Slide 40
40 More on using the Vector class To add a String object s to
the end of a Vector v v.add(s); To get the String object at the end
of the Vector v String s = (String) v.get(v.size()-1); To remove a
String object from the end of a Vector v String s = (String)
v.remove(v.size()-1); This both removes the object from the Vector
and stores the removed value into s
Slide 41
41 Multidimensional Array
Slide 42
42 Multidimensional arrays Many problems require information be
organized as a two- dimensional or multidimensional list Examples
Matrices Graphical animation Economic forecast models Map
representation Time studies of population change Microprocessor
design
Slide 43
43 Example Segment int[][] m = new int[3][]; m[0] = new int[4];
m[1] = new int[4]; m[2] = new int[4]; Produces When an array is
created, each value is initialized! m m[0]m[1]m[2] 00000000 0000
m[2][0]m[2][1]m[2][2]m[2][3]
m[0][0]m[0][1]m[0][2]m[0][3]m[1][0]m[1][1]m[1][2]m[1][3] m
Slide 44
44 Example Alternative int[][] m = new int[3][4]; Produces m
m[0]m[1]m[2] 00000000 0000 m[2][0]m[2][1]m[2][2]m[2][3]
m[0][0]m[0][1]m[0][2]m[0][3]m[1][0]m[1][1]m[1][2]m[1][3]
Slide 45
45 Multidimensional array visualization A multi-dimensional
array declaration (either one): int[][] m = new int[3][4]; How we
visualize it: 000 000 000 000 0 0 0 0 0 0 0 0 0 0 0 0 or
47 But what about adding variables? The add method takes an
Object as a parameter public void add (Object o) { Although we
havent seen it yet, this means you can add any object you want to
the vector Primitive types (i.e. variables) are not objects How can
they be added? The solution: wrapper classes!
Slide 48
48 Wrapper Classes
Slide 49
49 The Integer wrapper class This is how you add an int
variable to a Vector: int x = 5; Integer i = new Integer(x);
vector.add (i); // Integer j = (Integer) v.get(0); int y =
j.intValue(); Pretty annoying syntax well see how to get around it
in a bit
Slide 50
50 More on wrapper classes All the primitive types have wrapper
classes Usually, the names are just the capitalized version of the
type I.e. Double for double, Byte for byte, etc. Two exceptions:
int and char int has Integer char has Character
Slide 51
51 More on wrapper classes Consider this code: int x = 5;
vector.add (x); // int y = vector.get(0); Does this code work? It
shouldnt As we are adding a variable (not an object) to a vector
But it does work! Why?
Slide 52
52 Auto-boxing
Slide 53
53 Auto-boxing Java 1.5 will automatically wrap a primitive
value into its wrapper class when needed And automatically unwrap a
wrapper object into the primitive value So Java translates the
previous code into the following: int x = 5; vector.add (new
Integer(x)); // int y = ((Integer)vector.get(0)).intValue(); This
is called autoboxing And auto-unboxing (unauto-boxing?) This does
not work in Java 1.4 or before
Slide 54
54 More on auto-boxing Consider the following code: Double d =
7.5; Double e = 6.5; Double f = d + e; System.println (f); This is
doing a lot of auto-boxing (and auto-unboxing): Double d = new
Double(7.5); Double e = new Double(6.5); Double f =
newDouble(d.doubleValue() + e.doubleValue()); System.println
(f);
Slide 55
55 Method Invocation Order
Slide 56
1. Direct Mapping 2. Widening 3. Autoboxing 4. Variable
Arguments Consider this: public static void go(Long n)
{System.out.println(Long);} public static void go(Short n)
{System.out.println(Short);} public static void go(int n)
{System.out.println(int);} short y = 6; long z = 7; go(y); go(z);
Output: int Long
Slide 57
Binary Literal // binary literals int binVal = 0b00001000;
System.out.println(binVal); // hex literals int hexVal = 0xa;
System.out.println(hexVal);
Slide 58
Decisions Jiafan Zhou
Slide 59
59 Logical Expressions
Slide 60
60 Logical expressions There are three primary logical
operators for manipulating logical values Logical and Logical or
Logical not The operators work as most of us would expect
Slide 61
61 Truth tables Truth tables Lists all combinations of operand
values and the result of the operation for each combination pq p
and q False FalseFalse False TrueFalse True FalseFalse True
TrueTrue
Slide 62
62 Or and not truth tables pq p or q False FalseFalse False
TrueTrue True FalseTrue True TrueTrue pnot p False True True
False
Slide 63
63 A boolean type Java has the logical type boolean Type
boolean has two literal constants true false Operators The and
operator is && Dont use & The or operator is || Dont
use | The not operator is !
Slide 64
64 Defining boolean variables Local boolean variables are
uninitialized by default boolean isWhitespace; boolean
receivedAcknowledgement; boolean haveFoundMissingLink;
66 Assignment vs. comparison = is the assignment operator It
copies the value on the right to the location on the left Consider:
int x; x = 5; The value 5 is copied to the spot x in memory == is
the comparison operator Returns a boolean (true or false) if the
two sides are equal Consider: int x = 5; System.out.println (x ==
5); System.out.println (x == 6); Prints out true, false
Slide 67
67 Other operators Equality operators == and != Operator ==
Returns true if the operands have the same value; otherwise,
returns false This is not the assignment operator! Operator !=
Returns true if the operands have different values; otherwise,
returns false The operators work with all types of values
Slide 68
68 Evaluating boolean expressions Suppose boolean p = true;
boolean q = false; boolean r = true; boolean s = false; What is the
value of p p && s !s p == q q q != r p && r r == s
q || s q != s
Slide 69
69 Evaluating boolean expressions Suppose int i = 1; int j = 2;
int k = 2; char c = '#'; char d = '%'; char e = '#'; What is the
value of j == k i != k i == j j != k c == e d != e c == d c !=
e
Slide 70
70 Ordering operators Java provides ordering operators for the
primitive types Four ordering operators,, = They correspond to
mathematical operators of, , and Together the equality and ordering
operators are known as the relational operators False is less than
true
Slide 71
71 Evaluation boolean expressions Suppose int i = 1; int j = 2;
int k = 2; What is the value of i < j j < k i = k i >=
k
Slide 72
72 Unicode values Character comparisons are based on their
Unicode values Characters 0, 1, 9 have expected order Character 0
has the encoding 48 Character 1 has the encoding 49, and so on.
Upper case Latin letters A, B, Z have expected order Character A
has the encoding 65, character B has the encoding 66, and so on.
Lower case Latin letters a, b, z have expected order Character a
has the encoding 97 Character b has the encoding 98, and so
on.
Slide 73
73 Evaluation boolean expressions Suppose char c = '2'; char d
= '3'; char e = '2'; What is the value of c < d c < e c = e c
>= e
Slide 74
74 if statement
Slide 75
75 Conditional constructs Provide Ability to control whether a
statement list is executed Two constructs If statement if if-else
if-else-if Switch statement
Slide 76
76 Basic if statement Syntax if (Expression) Action If the
Expression is true then execute Action Action is either a single
statement or a group of statements within braces For us, it will
always be a group of statements within braces Expression Action
truefalse
Slide 77
77 What an if statement executes An if statement executes the
next block of code A block is either: A single statement without
curly brackets: if (a == b) System.out.println (a==b!!!); A number
of statements enclosed by curly brackets: if (a == b) {
System.out.print (a); System.out.print (==); System.out.print (b);
System.out.println (!!!); }
Slide 78
78 Why we always use braces What is the output? int m = 5; int
n = 10; if (m < n) ++m; ++n; System.out.println(" m = " + m + "
n = + n);
Slide 79
79 if-else statement
Slide 80
80 The if-else statement Syntax if (Expression) Action 1 else
Action 2 If Expression is true then execute Action 1 otherwise
execute Action 2 The actions are either a single statement or a
list of statements within braces Expression Action 1 Action 2 true
false
Slide 81
81 if-else-if statement
Slide 82 0) { Same results as previous segment but this segment
better expresses the meaning of what is going on We can change the
whitespace of the code">
82 if (number == 0) { System.out.println("zero"); } else
If-else-if Consider System.out.println("positive"); } else {
System.out.println("negative"); } } { These braces arent needed if
(number > 0) { Same results as previous segment but this segment
better expresses the meaning of what is going on We can change the
whitespace of the code
Slide 83
83 ?: notation
Slide 84
84 Finding the minimum value Consider: // z is to hold the
minimum of x and y if ( x < y ) z = x; else z = y ; Another way
to do this: z = (x 0) System.out.println("positive"); else
System.out.println("negative"); else
System.out.println("zero");">
85 The ?: notation Only works when both cases return a value!
Meaning when both cases are expressions Example: z = (x 0) ?
"positive : "negative") : "zero); if (number != 0) if (number >
0) System.out.println("positive"); else
System.out.println("negative"); else
System.out.println("zero");
Slide 86
86 switch statement
Slide 87
87 Switch statement Software engineers often confronted with
programming tasks where required action depends on the values of
integer expressions The if-else-if construct can be used Separately
compare the desired expression to a particular value If the
expression and value are equal, then perform the appropriate action
Because such programming tasks occur frequently Java includes a
switch statement The task is often more readable with the switch
then with the if-else-if
Slide 88
88 A switch statement example if (a == 0) System.out.println
(zero); else if (a == 1) System.out.println (one); else if (a == 2)
System.out.println (two); else if (a == 3) System.out.println
(three); else if (a == 4) System.out.println (four); else
System.out.println (five+); switch (a) { case 0: System.out.println
(zero); break; case 1: System.out.println (one); break; case 2:
System.out.println (two); break; case 3: System.out.println
(three); break; case 4: System.out.println (four); break; default:
System.out.println (five+); break; }
Slide 89
89 Testing for vowel-ness switch (ch) { case 'a': case 'A':
case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case
'u': case 'U': System.out.println("vowel); break; default:
System.out.println("not a vowel); }
Slide 90
90 Testing for vowel-ness switch (ch) { case 'a': case 'A':
case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case
'u': case 'U': System.out.println("vowel); break; default:
System.out.println("not a vowel); } The break causes an exiting of
the switch Handles all of the other cases
Slide 91
91 Processing a request System.out.print("Enter a number: ");
int n1 = stdin.nextInt(); System.out.print("Enter another number:
"); int n2 = stdin.nextInt(); System.out.print("Enter desired
operator: "); char operator = stdin.nextLine().charAt(0); switch
(operator) { case '+' : System.out.println((n1 + n2)); break; case
'-' : System.out.println(n1 - n2); break; case '*' :
System.out.println(n1 * n2); break; case '/' :
System.out.println(n1 / n2); break; default:
System.out.println(Illegal request); }
Slide 92
Switch on String Prior to Java 7, switch works on primitive
types Starting from Java7, Switch supports the String data type
StringSwithDemo.java
Slide 93
93 Object equality
Slide 94
94 Testing variables for equality Consider
System.out.print("Enter an integer number: "); int n1 =
stdin.nextInt(); System.out.print("Enter another integer number:
"); int n2 = stdin.nextInt(); if (n1 == n2) {
System.out.println("Same"); } else {
System.out.println(Different"); } What is the output if the user
enters 88 and 3? What is the output if the user enters 88 both
times?
96 Testing objects for equality Memory looks like The
comparison is between the references! Thus, s1 and s2 are the same
(they refer to the same object) "pastel"s1 s2
Slide 97
97 Testing objects for equality Consider
System.out.print("Enter a string: "); String s1 = stdin.nextLine();
System.out.print("Enter another string: "); String s2 =
stdin.nextLine(); if (s1 == s2) { System.out.println("Same"); }
else { System.out.println("Different"); } What is the output if the
user enters "pastel" both times?
Slide 98
98 Testing objects for equality When it is executed
System.out.print("Enter a string: "); String s1 = stdin.nextLine();
System.out.print("Enter another string: "); String s2 =
stdin.nextLine(); Memory looks like As a result no matter what is
entered s1 and s2 are not the same They refer to different objects
"pastel"s1 " "s2
Slide 99
99 Comparing strings for equality Consider: String u = new
String("hello"); String v = new String("hello"); System.out.println
(u == v); What gets printed? false Consider: String s = "hello";
String t = "hello"; System.out.println (s == t); What gets printed?
true Huh? These arent the exact same thing
Slide 100
100 Testing operators for equality Consider
System.out.print("Enter a string: "); String s1 = stdin.nextLine();
System.out.print("Enter another string: "); String s2 =
stdin.nextLine(); if (s1.equals(s2)) { System.out.println("Same");
} else { System.out.println("Different"); } Tests whether s1 and s2
represent the same object Most classes have a method equals(). It
compares the objects themselves, not the references.
Slide 101
101 Short-circuitevaluation
Slide 102
102 Short-circuit evaluation The value of a logical expression
can be known before all the operands have been considered If left
operand of && is false, then the value must be false If
left operand of || is true, then the value must be true Java uses
these properties to make logical operations efficient Evaluates
left operand before it evaluates right operand If the operator
value is determined from the left operand, then the right operand
is not evaluated The operation is short-circuited
Slide 103
103 Short-circuit evaluation Short-circuit evaluation is useful
when some property must be true for some other expression to be
evaluated Suppose you are interested in knowing whether scoreSum
divided by nbrScores is greater than value The condition can be
evaluated only if nbrScores is nonzero The following expression
correctly represents the condition (nbrScores != 0) &&
((scoreSum / nbrScores) > value)
Slide 104
104 Short-circuit evaluation Assume we have a returnsFalse()
method from a foo object It returns false And it prints
returnsFalse() called And a returnsTrue() method Consider: if (
foo.returnsFalse() && foo.returnsTrue() ) { } if (
foo.returnsTrue() && foo.returnsFalse() ) { } if (
foo.returnsFalse() || foo.returnsTrue() ) { } if (
foo.returnsTrue() || foo.returnsFalse() ) { } returnsFalse() called
returnsTrue() called returnsFalse() called returnsTrue() called
Output
Slide 105
Consider this if ( foo.returnsFalse() & foo.returnsTrue() )
{ } if ( foo.returnsTrue() & foo.returnsFalse() ) { } if (
foo.returnsFalse() | foo.returnsTrue() ) { } if ( foo.returnsTrue()
| foo.returnsFalse() ) { } 105
Slide 106 >" depends on sign extension) unsigned right shift
operator >>> shifts a zero into the leftmost position
106">
Bitwise and Bit Shift Operators The bitwise operators allow you
to manipulate individual bits in an integral primitive data type.
& operator performs a bitwise AND operation. ^ operator
performs a bitwise exclusive OR operation. | operator performs a
bitwise inclusive OR operation. complement operator ~ inverts a bit
pattern > shifts a bit pattern to the right (the leftmost
position after ">>" depends on sign extension) unsigned right
shift operator >>> shifts a zero into the leftmost
position 106
Slide 107
class BitDemo { public static void main(String[] args) { int
bitmask = 0x000F; int val = 0x2222; System.out.println(val &
bitmask); } 107 2
Slide 108
108 Java looping Options while do-while for Allow programs to
control how many times a statement list is executed
Slide 109
109 While syntax and semantics Logical expression that
determines whether Action is to be executed while ( Expression )
Action Action is either a single statement or a statement list
within braces
Slide 110
110 Converting text to strictly lowercase public static void
main(String[] args) { Scanner stdin = new Scanner (System.in);
System.out.println("Enter input to be converted:"); String
converted = ""; while (stdin.hasNext()) { String currentLine =
stdin.nextLine(); String currentConversion =
currentLine.toLowerCase(); converted += (currentConversion + "\n");
} System.out.println("\nConversion is:\n" + converted); }
Slide 111
111 The For statement
Slide 112
112 The For Statement currentTerm = 1; for ( int i = 0; i <
5; ++i ) { System.out.println(currentTerm); currentTerm *= 2; }
After each iteration of the body of the loop, the update expression
is reevaluated The body of the loop iterates while the test
expression is true int Initialization step is performed only once
-- just prior to the first evaluation of the test expression The
body of the loop displays the current term in the number series. It
then determines what is to be the new current number in the
series
Slide 113
113 for statement syntax Logical test expression that
determines whether the action and update step are executed for (
ForInit ; ForExpression ; ForUpdate ) Action Update step is
performed after the execution of the loop body Initialization step
prepares for the first evaluation of the test expression The body
of the loop iterates whenever the test expression evaluates to
true
Slide 114
114 for vs. while A for statement is almost like a while
statement for ( ForInit; ForExpression; ForUpdate ) Action is
ALMOST the same as: ForInit; while ( ForExpression ) { Action;
ForUpdate; } This is not an absolute equivalence! Well see when
they are different in a bit
Slide 115
115 Variable declaration You can declare a variable in any
block: while ( true ) { int n = 0; n++; System.out.println (n); }
System.out.println (n); Variable n gets created (and initialized)
each time Thus, println() always prints out 1 Variable n is not
defined once while loop ends As n is not defined here, this causes
an error
Slide 116
116 for vs. while An example when a for loop can be directly
translated into a while loop: int count; for ( count = 0; count
< 10; count++ ) { System.out.println (count); } Translates to:
int count; count = 0; while (count < 10) { System.out.println
(count); count++; }
Slide 117
117 Enhanced for loop An enhanced for loop, new to Java 6, is a
specialised for loop that simplifies the looping through a
collection or enums. long[] longArray = {1L, 5L, 10L, 13L} for
(long value: longArray) { System.out.println (value); } It works on
enums as well: enum Color {RED, GREEN BLUE} for (Color c:
Color.values()) { System.out.println(c); }
Slide 118
118 do-while loops
Slide 119
119 The do-while statement Syntax do Action while (Expression)
Semantics Execute Action If Expression is true then execute Action
again Repeat this process until Expression evaluates to false
Action is either a single statement or a group of statements within
braces Action true false Expression
Slide 120
120 while vs. do-while If the condition is false: while will
not execute the action do-while will execute it once while ( false
) { System.out.println (foo); } do { System.out.println (foo); }
while ( false ); never executed executed once
Slide 121
121 while vs. do-while A do-while statement can be translated
into a while statement as follows: do { Action; } while (
WhileExpression ); can be translated into: boolean flag = true;
while ( WhileExpression || flag ) { flag = false; Action; }
Slide 122
122 Loop controls
Slide 123
123 The continue keyword The continue keyword will immediately
start the next iteration of the loop The rest of the current loop
is not executed But the ForUpdate part is, if continue is in a for
loop for ( int a = 0; a