Download presentation
Presentation is loading. Please wait.
Published bySheena Reynolds Modified over 9 years ago
1
Arrays Jiafan Zhou
2
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
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 …
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();
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[];
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
7
7 Where we’ve 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)
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
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…
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]);
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
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;
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
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;
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()
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);
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]
18
18 How Java represents arrays Consider int[] a = { 1, 2, 3, 4, 5 }; a 1 2345 + … Array - length = 5 - data = 12345
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;
20
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] + "'"); } } }
21
21 Program Demo MainParameters.java Via Eclipse Via the command line
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
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]; } }
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
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]
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
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
28
28 Limitations of arrays You can’t 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… Let’s call the class Vector As we are basically writing the java.util.Vector class
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…
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
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? We’ll see that a bit later… But briefly, it means the array can store any object
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
33
33 Increasing the Vector’s array’s 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; }
34
34 Methods can be private as well Notice that the increaseCapacity() method is called only by the add() method when necessary It’s 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
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; }
36
36 Miscellaneous other methods public int size() { return size; } public Object get (int which) { return array[which]; }
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; }
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); }
39
39 The “real” Vector class Java provides a Vector class In java.util It contains all of the methods shown
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
41
41 Multidimensional Array
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
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
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]
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
46
46 Explicit Initialization Segment int c[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8, 9}}; Produces
47
47 But what about adding variables? The add method takes an Object as a parameter public void add (Object o) { Although we haven’t 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!
48
48 Wrapper Classes
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 – we’ll see how to get around it in a bit…
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
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 shouldn’t As we are adding a variable (not an object) to a vector But it does work! Why?
52
52 Auto-boxing
53
53 Auto-boxing Java 1.5 will automatically “wrap” a primitive value into it’s 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
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);
55
55 Method Invocation Order
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
57
Binary Literal // binary literals int binVal = 0b00001000; System.out.println(binVal); // hex literals int hexVal = 0xa; System.out.println(hexVal);
58
Decisions Jiafan Zhou
59
59 Logical Expressions
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
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
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
63
63 A boolean type Java has the logical type boolean Type boolean has two literal constants true false Operators The and operator is && Don’t use & The or operator is || Don’t use | The not operator is !
64
64 Defining boolean variables Local boolean variables are uninitialized by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink;
65
65 Defining boolean variables Local boolean variables with initialization boolean canProceed = true; boolean preferCyan = false; boolean completedSecretMission = true;
66
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
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
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
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
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
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 j >= k i >= k
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.
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 d >= e c >= e
74
74 if statement
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
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
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 (“!!!”); }
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);
79
79 if-else statement
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
81
81 if-else-if statement
82
82 if (number == 0) { System.out.println("zero"); } else If-else-if Consider System.out.println("positive"); } else { System.out.println("negative"); } } { These braces aren’t 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
83
83 ?: notation
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<y) ? x : y; Notice no braces!
85
85 The ?: notation Only works when both “cases” return a value! Meaning when both “cases” are expressions Example: z = (x<y) ? x : y; Thus, you can’t put a print statement in there! Can be difficult to read System.out.println ((number != 0) ? ((number > 0) ? "positive“ : "negative") : "zero“); if (number != 0) if (number > 0) System.out.println("positive"); else System.out.println("negative"); else System.out.println("zero");
86
86 switch statement
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
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; }
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“); }
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
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“); }
92
Switch on String Prior to Java 7, switch works on primitive types Starting from Java7, Switch supports the String data type StringSwithDemo.java
93
93 Object equality
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?
95
95 Testing objects for equality Consider String s1 = “pastel”; String s2 = s1; if (s1 == s2) { System.out.println("Same"); } else { System.out.println("Different"); }
96
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
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?
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
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 aren’t the exact same thing
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.
101
101 Short-circuitevaluation
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
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)
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
105
Consider this… if ( foo.returnsFalse() & foo.returnsTrue() ) { } if ( foo.returnsTrue() & foo.returnsFalse() ) { } if ( foo.returnsFalse() | foo.returnsTrue() ) { } if ( foo.returnsTrue() | foo.returnsFalse() ) { } 105
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 left signed right shift operator >> 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
107
class BitDemo { public static void main(String[] args) { int bitmask = 0x000F; int val = 0x2222; System.out.println(val & bitmask); } 107 2
108
108 Java looping Options while do-while for Allow programs to control how many times a statement list is executed
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
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); }
111
111 The For statement
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
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
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! We’ll see when they are different in a bit
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
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++; }
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); }
118
118 do-while loops
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
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
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; }
122
122 Loop controls
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 <= 10; a++ ) { if ( a % 2 == 0 ) { continue; } System.out.println (a + " is odd"); } Output:1 is odd 3 is odd 5 is odd 7 is odd 9 is odd
124
124 The break keyword The break keyword will immediately stop the execution of the loop Execution resumes after the end of the loop for ( int a = 0; a <= 10; a++ ) { if ( a == 5 ) { break; } System.out.println (a + " is less than five"); } Output:0 is less than five 1 is less than five 2 is less than five 3 is less than five 4 is less than five
125
Homework
126
Practice yourself with the java.util.Arrays class to manipulate arrays. For the following problem domain, implement using proper decision operators. Design a menu for a banking system, the menu should look like this: 1. Log in 2. Deposit 3. Withdraw 4. Transfer 5. Exit If user enters 1, it should further allows user to enter username/password. For any input entered, the menu should reprinted again unless user enters 5. Exit Hint: Consider to create a BankAccount class with attributes and methods. Use while or for loop for printing menu. Use if or switch for condition checks.
127
Questions & Answers
128
128 Mock Exam Questions: Question 56 Given: 11. public static void main(String[] args) { 12. String str = “null’; 13. if (str == null) { 14. System.out.println(”null”); 15. } else (str.length() == 0) { 16. System.out.println(”zero”); 17. } else { 18. System.out.println(”some”); 19. } 20. } ‘What is the result? A. null B. zero C. some D. Compilation fails. E. An exception is thrown at runtime.
129
129 Mock Exam Questions: Question 58 Given: 10.int x=0; 11.int y=10; 12. do { l3. y--; 14. ++x; 15. } while (x < 5); 16. System.out.print(x + “,“ + y); What is the result? A. 5,6 B. 5,5 C. 6,5 D. 6,6
130
130 Mock Exam Questions: Question 3 Given: 11. public class Test { 12. public static void main(String [] args) { 13. int x =5; 14. boolean b1 = true; 15. boolean b2 = false; 16. 17.if((x==4) && !b2) 18. System.out.print(”l “); 19. System.out.print(”2 “); 20. if ((b2 = true) && b1) 21. System.out.print(”3 “); 22. } 23. } What is the result? A. 2 B. 3 C. 1 2 D. 2 3 E. 1 2 3 F. Compilation fails. G. Au exceptional is thrown at runtime.
131
131 Mock Exam Questions: Question 29 Given: 55. int []x= {1, 2,3,4, 5}; 56.int y[] =x; 57. System.out.println(y[2]); Which is true? A. Line 57 will print the value 2. B. Line 57 will print the value 3. C. Compilation will fail because of an error in line 55. D. Compilation will fail because of an error in line 56.
132
132 Mock Exam Questions: Question 31 Which two code fragments correctly create and initialize a static array of int elements? (Choose two.) A. static final int[] a = { 100,200 }; B. static final int[] a; static { a=new int[2]; a[0]=100; a[1]=200; } C. static final int[] a = new int[2] { 100,200 }; D. static final int[] a; static void init() { a = new int[3]; a[0]=100; a[1]=200; }
133
133 Mock Exam Questions: Question 32 Given: 11. public class Ball { 12. public enum Color { RED, GREEN, BLUE }; 13. public void foo() { 14. // insert code here 15. { System.out.println(c); } 16. } 17. } Which code inserted at line 14 causes the foo method to print RED, GREEN, and BLUE? A. for( Color c : Color.values()) B. for( Color c = RED; c <= BLUE; c++) C. for( Color c; c.hasNext() ; c.next()) D. for( Color c = Color[0]; c <= Color[2]; c++) E. for( Color c = Color.RED; c <= Color.BLUE; c++)
134
134 Mock Exam Questions: Question 35 Given: 11. public static void main(String[] args) { 12. Object obj =new int[] { 1,2,3 }; 13. int[] someArray = (int[])obj; 14. for (int i: someArray) System.out.print(i +“ “) 15. } ‘What is the result? A. 1 2 3 B. Compilation fails because of an error in line 12. C. Compilation fails because of an error in line 13. D. Compilation fails because of an error in line 14. E. A ClassCastException is thrown at runtime.
135
135 Mock Exam Questions: Question 44 Click the Exhibit button. 1. public class A { 2. public String doit(int x, int y) { 3. return “a”; 4. } 5. 6. public String doit(int... vals) { 7. return “b”; 8. } 9. } Given: 25. A a=new A(); 26. System.out.println(a.doit(4, 5)); What is the result? A. Line 26 prints “a” to System.out. B. Line 26 prints ‘b” to System.out. C. An exception is thrown at line 26 at runtime. D. Compilation of class A will fail due to an error in line 6.
136
136 Mock Exam Questions: Question 52 Given: 11. public class Test { 12. public enum Dogs {collie, harrier, shepherd}; 13. public static void main(String [] args) { 14. Dogs myDog = Dogs.shepherd; 15. switch (myDog) { 16. case collie: 17. System.out.print(”collie “); 18. case default: 19. System.out.print(”retriever “); 20. case harrier: 21. System.out.print(”harrier “); 22. } 23. } 24. } ‘What is the result? A. harrier B. shepherd C. retriever D. Compilation fails. E. retriever harrier F. An exception is thrown at runtime.
137
137 Mock Exam Questions: Question 53 Given: 12. public class Test { 13. public enum Dogs {collie, harrier}; 14. public static void main(String [] args) { 15. Dogs myDog = Dogs.collie; 16. switch (myDog) { 17. case collie: 18. System.out.print(”collie “); 19. case harrier: 20. System.out.print(”harrier “); 21. } 22. } 23. } What is the result? A. collie B. harrier C. Compilation fails. D. collie harrier E. An exception is thrown at runtime.
138
138 Mock Exam Questions: Question 54 Given: 11. public void testIfA() { 12. if(testIfB(”True”)) { 13. System.out.println(”True”); 14. } else { 15. System.out.println(”Not true”); 16. } 17. } 18. public Boolean testIfB(String str) { 19. return Boolean.valueOf(str); 20. } What is the result when method testIfA is invoked? A. True B. Not true C. An exception is thrown at runtime. D. Compilation fails because of an error at line 12. E. Compilation fails because of an error at line 19.
139
139 Mock Exam Questions: Question 55 Given: 11. public static void main(String[] args) { 12. Integer i = new Integer(1) + new Integer(2); 13. switch(i) { 14. case 3: System.out.println(”three”); break; 15. default: System.out.println(”other”); break; 16. } 17. } ‘What is the result? A. three B. other C. An exception is thrown at runtime. D. Compilation fails because of an error on line 12. E. Compilation fails because of an error on line 13. F. Compilation fails because of an error on line 15.
140
140 Mock Exam Questions: Question 60 Given: 35. int x= 10; 36. do { 37. x--; 38. } while(x< 10); How many times will line 37 be executed? A. ten times B. zero times C. one to me times D. more than ten times
141
141 Mock Exam Questions: Question 63 Given: 11. public static void main(String[] args) { 12. for (int i=0;i<= 10;i++){ 13. if( i>6) break; 14. } 15. System.out.println(i); 16. } What is the result? A. 6 B. 7 C. 10 D. 11 E. Compilation fails. F. An exception is thrown at runtime.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.