Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 1 Sun Certified Java 1.4 Programmer Chapter 3 Notes Gary Lance

Similar presentations


Presentation on theme: "Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 1 Sun Certified Java 1.4 Programmer Chapter 3 Notes Gary Lance"— Presentation transcript:

1 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 1 Sun Certified Java 1.4 Programmer Chapter 3 Notes Gary Lance glance44@comcast.net http://home.comcast.net/~glance44/microhard/java2.html

2 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 2 Object References Given MyObject obj = new MyObject(); What is “obj”, if it is not null? Memory storage on the heap for instance of MyObject address of instance location obj new MyObject()

3 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 3 Assignment Operators A byte is 8 bits, and ranges from 2 -7 to 2 7 -1 (or -128 to 127, which you should memorize). byte a = 10; // digits are always int, without casting The above is OK, since 10 is ‘0000 1010’ in bit notation, so it can be represented exactly. byte b = 128; // COMPILER ERROR! Clearly, we can’t represent 128 in 8 bits. int num = 10; byte b = num;// not allowed, as num may be invalid compiler error is: POSSIBLE LOSS OF PRECISION byte b = (byte)num;//cast to byte first. This is OK. int num = 200; byte b = (byte)num;// OK The above prints out as “-56”, which is wrong. But it compiles and runs.

4 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 4 Assignment of References Create a reference to an object, and copy that reference into another reference (obj2). MyObject obj1 = new MyObject(); MyObject obj2 = obj1; Both obj1 and obj2 refer to the same memory location. IMPORTANT: obj1 and obj2 are not the object; they hold the address in random access memory (RAM) where the object is located. instance of MyObject address of object obj1 new MyObject() address of object obj2

5 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 5 References Can Change Values in Memory, but NOT Location public class Person { private String firstName, lastName; public Person(String firstName, String lastName){ setFirstName( firstName ); } public void setFirstName( String firstname){ this.firstName = firstName; } public static void main(String[] args){ Person person = new Person( “Abraham”, “Lincoln”); person.setFirstName(“Mary”); } address of object person initial Person object “Abraham” “Lincoln” address of object person Person object after change “Mary” “Lincoln” location is the same, but the data in that memory is changed.

6 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 6 Strings are Immutable When you concatenate String objects, the object that is returned is a new String object. How does that happen? Chapter 6. (String and StringBuffer classes are involved). In the code below, str1 and str2 initially hold the same value, which is the reference to “abc”. public class Strings { public static void main(String[] args){ String str1 = “abc” String str2 = str1; } “abc” str1 str2

7 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 7 Concatenation of Strings But when we concatenate (str += “def”), this really is what happens: str2 = new StringBuffer().append(“abc”).append(“def”).toString(); 1.A StringBuffer object is created, and it can grow (unlike an array or a String). 2.Characters are appended to the buffer, 3.It is converted to a String using toString(). This happens on the rhs of the equal. 4.A reference to the new String is returned by the toString() method, 5.That value is placed in the location of str2. That’s quite a bit of work, but that’s really what happens. (I don’t think this is in the text). So, the value in the reference str2 changes to a value, which is the new location of the concatenated String object. public class Strings { public static void main(String[] args){ String str1 = “abc” String str2 = str1; str2 += “def”; } “abc” str1 str2 “abcdef”

8 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 8 Precedence http://www.uni-bonn.de/~manfear/javaoperators.php

9 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 9 Comparison Operators There are four comparison operators that are used to compare ints, fp numbers, or chars:, =. The result is always a boolean (true or false). int x = 8; // enter block if x<9 returns true if ( x < 9 ) {...}

10 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 10 Comparison Operators class CompareTest { public static void main(String[] args){ boolean b = 100 > 99; System.out.println(“b is “ + b); } Look at the statement: boolean b = 100 > 99; Notice that ‘>’ has higher precedence than ‘=‘ (priority = 6 compared to priority 14 on the precedence chart). So, ‘100 < 99’ is done first, which returns ‘false’. Then variable ‘b’ of type ‘boolean’ is created. Finally, the value ‘false’ is assigned to ‘b’.

11 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 11 instanceof Operator First of all, instanceof is all small letters (which can confuse us). instanceof is a binary operator, which means it is like ‘+’, which is surrounded by values on the left and right. The lhs is an object reference. The rhs is a class or interface name. instanceof operation returns a boolean, if it is used correctly. There will be a compiler error if the lhs is not related to the rhs by inheritance. instanceof is used to compare ONLY objects related by hierarchy, so a complete discussion must come after we talk about inheritance. null is never an instance of anything, so null instanceof X returns false, where X is any class or interface.

12 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 12 instanceof Operator WHAT IS THE OUTPUT? public class Practice { public static void main(String[] args){ EveryThing et = new EveryThing(); Object ob = new Object(); System.out.println(et instanceof EveryThing); System.out.println(et instanceof Object); System.out.println(ob instanceof Object); System.out.println(ob instanceof EveryThing); } class EveryThing { } Object EveryThing

13 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 13 instanceof Operator WHAT IS THE OUTPUT? public class Practice { public static void main(String[] args){ EveryThing et = new EveryThing(); SomeThing st = new SomeThing(); System.out.println(et instanceof SomeThing); System.out.println(st instanceof EveryThing); } class EveryThing {} class SomeThing extends EveryThing {} Object EveryThing SomeThing

14 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 14 Equality for Primitives Be careful: ‘=‘ and ‘==‘ are completely different. ‘=‘ is an assignment operator, which places whatever is returned on the rhs into the location of the variable on the lhs. ‘==‘ is a comparison operator for primitives, and it compares the value on the left with the value on the right. It returns true or false. What does the following code print? public class Practice { public static void main(String[] args){ int a = 9; System.out.println(a=9); System.out.println(a==9); if(a=9) System.out.println(new Date().toString()); }

15 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 15 Equality for Primitives Code doesn’t print anything. There is a compiler error because Date class is not in java.lang. What does the code print now? import java.util.Date; public class Practice { public static void main(String[] args){ int a = 9; System.out.println( a = 9 ); System.out.println( a == 9 ); if( a = 9 ) System.out.println(new Date().toString()); }

16 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 16 Equality for Primitives It still doesn’t print anything. Why? Because the if-structure requires a boolean (chapter 4). But the rhs of ‘a=9’ returns the int ‘9’, and it also places it in variable ‘a’, so it’s like “if(9)” So, we get another compiler error. Practice.java:7: incompatible types found : int required: boolean if(a = 9) ^ import java.util.Date; public class Practice { public static void main(String[] args){ int a = 9; if( a = 9 ) System.out.println(new Date().toString()); }

17 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 17 Equality for Primitives But, if we want to compare ‘a’ to the value 9, then we use “==“. The date is printed, because the test “ a==9 ” returns true. mport java.util.Date; public class Practice { public static void main(String[] args){ int a = 9; if( a == 9 ) System.out.println(new Date().toString()); }

18 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 18 Equality for References When we deal with ‘==‘ and references, we are asking the question: Are both reference variables holding the address of the same object? Equivalently, are the references referring to the same object? What is the output of the following code fragment? Person p1 = new Person(“Abe”, “Lincoln”); Person p2 = p1; Person p3 = new Person(“Abe”, “Lincoln”); System.out.println(p1 == p2); System.out.println(p1 == p3); System.out.println(p2 == p3);

19 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 19 Modulus Operator The result of 11 % 3 is the remainder of 11 divided by 3: 11/3 = 3 ⅔, so 11%3 = 2 How do you test if a number is even? If a number is even, it must not have a remainder after division by 2: int a =...;// ‘a’ must be an int if(a%2 == 0) System.out.println(“a is even”); else System.out.println(“a is odd”);// an int is either even or odd NOTE: in “a%2 == 2”, the modulus operator MUST have higher precedence than ‘==‘. From the precedence chart, we see that ‘%’ has priority 3, while ‘==‘ has a lower priority of 7.

20 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 20 String Concatenation The only overloaded operator in Java is ‘+’, as it is addition for numbers, and concatenation for Strings. String s1 = “abc”;// new String(“abc”); String s2 = “def”; String s3 = s1 + s2;// s3 = “abcdef”; int a = 5, b = 6; String s4 = s3 + a + b; Notice from page 8, priority 4, that ‘+’ for both addition and concatenation “draws from the left”. So, if the lhs of ‘+’ is a String, the operation is concatenation. If the lhs of ‘+’ is a String, and the rhs is a number, the number is treated as if it were a String: String s4 = s3 + String.valueOf(a) + String.valueOf(b);

21 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 21 String Concatenation What if the lhs of ‘+’ is a number? String s1 = “abc”;// new String(“abc”); int a = 5, b = 6; String s2 = a + b + s1; First add ‘a + b’, which is 11. Now, if either side of ‘+’ is a String, then we still concatenate. The value of s2 is “11abc”.

22 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 22 String Concatenation There are at least two ways to create a String out of any primitive: int a = 5; String s1 = “” + 5;// not preferred, but ok String s2 = String.valueOf(5); double d = 9.9; String s3 = String.valueOf(d);// valueOf is overloaded boolean b = true; String s4 = String.valueOf(b);

23 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 23 String Concatenation Finally, why does the following print 23 and not 5? int b = 2, c = 3; System.out.println(“” + b + c);

24 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 24 Increment and Decrement ++  increment--  decrement int x = 2, y = 3; if( (y == x++) | ( x < ++y ) ){ System.out.println( “(x,y) = <“ + x + “,” + y + “)” ); Parens come first. Also, from page 8, ‘|’ draws from the left, so the lhs of ‘|’ is evaluated before the rhs. Also, this bitwise logical operator, which ALWAYS evaluates both the lhs and the rhs. (y == x++)// postfix notation This is the same as: y == x;// 2 == 3 is false, so this is false x = x + 1;// x = x+1 = 2+1 = 3 Then, for the rhs of ‘|’:(x < ++y): This is the same as y = y + 1;// y = y+1 = 3+1 = 4 x < y;/ 3 < 4 is true Thus, we evaluate if(false | true), which is true since this is the ‘or’ test, which is true if one of the arguments is true. The printout occurs: (x,y) = (3,4)

25 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 25 Increment and Decrement final int x = 5; x++;// compiler error: can’t assign value

26 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 26 Shift Operators – Bit Manipulation “Shift operators are rarely used by most programmers; therefore, they will most definitely be on the exam.” page 168. x >> n: x right shifted n times: “sign extension”. All bits shift to the right. But, whatever was in MSD is copied to the MSD. LSD bits are lost. Negatives remain as negatives, and positives remain as positives. x << n: x left shifted n times: right side always filled in with 0’s. Lose MSD. x >>> n: unsigned right shift: same as >>, except 0’s go into MSD. Therefore, for positive numbers, >> is identical to >>

27 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 27 Hex  16 You can represent a number in hex notation. Note that since each group of hex digits can be at most 15 = 2 4 -1, each hex is made up of 4 digits, with shorthand notation in parentheses below. 0 (0)1 (1)2 (2)3 (3)4 (4)5 (5)6 (6)7 (7) 00000001001000110100010101100111 8 (8)9 (9)10 (a)11 (b)12 (c)13 (d)14 (e)15 (f) 10001001101010111100110111101111

28 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 28 int in Binary and Hex Represent the int 63 in binary and hex. Remember that int has 32 bits, which is 8 groups of 4: Notice that 64 = 2 6, so 63 = 2 6 – 1: 64: 0000 0000 0000 0000 0000 0000 0100 0000 63: 0000 0000 0000 0000 0000 0000 0011 1111 63 in hex: 0x0000003f (see last page) 63 << 3: 0000 0000 0000 0000 0000 0001 1111 1000 = 0x000001f8

29 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 29 Left shifting What is the output? (+ has higher priority than <<, which is why we use parens around x<<4. Otherwise, the rhs of << would be a String, which can’t be, as the rhs MUST be an int. It would result in a compiler error.) public class Practice { public static void main(String[] args){ int x = 0x000001; for(int i = 0; i < 6; i++) System.out.print ( (x << 4) + “ “); } Output is 16 16 16 2 4 (= 16) is returned in ‘x << 4’. This makes sense, because x << n is really the same as x * 2 4. One would expect the same with the right shift operator, since that is like division.

30 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 30 Left shifting What is the output? Typically, everything has higher priority than =. public class Practice { public static void main(String[] args){ int x = 0x000001; for(int i = 0; i < 6; i++){ System.out.print (x = x << 4); System.out.print(“ “); } Output is 16 256 4096 65536 1048576 16777216 Note where the assignment to x is done. Since << has higher precendence than =, x<<4 is done first, which returns that value, and then that value is assigned to x. But since x<<4 is returned, it is printed out.

31 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 31 Shifting by Large Numbers If we shift and int by more than 32 places, then we take the modulus first. So, ‘x << 40’ is the same as ‘x << 40%32’. (We don’t need parens around ’40%32’ since % has higher precedence than <<.) The following prints out 2 4 8. public class Practice { public static void main(String[] args){ int x = 1; for(int i = 0; i < 3; i++){ System.out.print( x = x << 33); //Last statement is the same as //System.out.print( x = x << 33%32); System.out.print( “ “); }

32 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 32 Bitwise Operators (&, |, ^) These operators operate on the ints by first converting them to their bitwise representation. To get started, know this truth table by heart (^ is exclusive or, XOR, which is 1 if operands are different): XY& (AND)| (OR)^ 00000 01011 10011 11110

33 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 33 Bitwise Operator Examples public class Practice { public static void main(String[] args){ int a = 0x00000066;// 0110 0110 int b = 0x00000096;// 1001 0110 System.out.println( "0x00000066 & 0x00000096 = " + (a&b)); System.out.println( "0x00000066 | 0x00000096 = " + (a|b)); System.out.println( "0x00000066 ^ 0x00000096 = " + (a^b)); } 0x00000066 & 0x00000096 = 6 = 0000 0110 0x00000066 | 0x00000096 = 246 = 1111 0110 = 256 – 16 + 6 0x00000066 ^ 0x00000096 = 240 = 1111 0000 = 256 – 16

34 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 34 Bitwise Complement Operator ~ ~ just changes all 0’s to 1’s, and all 1’s to 0’s. Note: 0xffffffff = -1 0xfffffffe = -2 0xfffffffd = -3 etc... int x = ~8; Since 8 is 0x00000008, which expands to 0000 0000 0000 0000 0000 0000 0000 1000 We have ~8 is 1111 1111 1111 1111 1111 1111 1111 0111 which is 0xfffffff7 = -9

35 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 35 Conditional Operator This is the only ternary (3 operand) operator in Java (boolean expr) ? [eval. if true] : [eval if false] What is printed? public class Practice { public static void main(String[] args){ int x = 10; int y = ( x == 190 ) ? 1 : 2; System.out.println(y); }

36 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 36 Primitive Casting There is implicit and explicit casting. If you are storing a type into a larger type (like putting a float into a double), no cast is required. This is known as widening, and happens implicitly. If you are storing a type into a smaller type (like putting a double into a float), your may lose data. You must use a cast, or you will get a compiler error.

37 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 37 Primitive Casting Putting the int into the long is ok, as 32 bits can fit into 64 bits without losing any data. But when you put an int into a short, you are trying to put 32 bits into 16 bits. This may result in loss of precision if the int is greater than 32,767 or smaller than -32,768. So, the compiler forces you to use a cast, so that you are aware of the problems, which is the truncation of the 16 most significant bits. public class Practice { public static void main(String[] args){ int x = 1000000; long y = x;// ok, since this is widening short z = x;// needs cast (short)x }

38 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 38 Primitive Casting Since whole numbers are ints by default, to force the compiler to recognize a number as a long, append ‘L’ or ‘l’ to the end of the number. NOTE: it is always better to use ‘L’ instead of ‘l’, for obvious reasons. Similarly, to make a fp number a float, append ‘F’ or ‘f’ to that number. long num = 123L; float f = 12.3F; Note: use a cast for short: short s = (short)123;

39 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 39 Logical Operators && (and)|| (or) These are short circuit operators. Suppose f and g are operations that return a boolean. ‘f && g’ is true if both f and g are true. So, if f is false, ‘f && g’ can never be true. So, g is not evaluated if f is false. This is what is meant by short circuiting. Similarly, ‘f || g’ is true if either f or g is true. So, if f is true, there is no need to evaluate g, since ‘f || g’ will be true already.

40 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 40 Passing References in Methods When you have a method that has an object as an argument, then you are passing the address of that object to the method. That is, you are copying the reference into the parameter of the method, so that the argument’s value is copied into another variable. So, you will not be able to change the value of the argument originally used, because a copy is made. However, you can use mutators of the object’s class to change the values of the instance variables, using that copy of the reference in the method.

41 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 41 Passing References public class Practice { public static void main(String[] args){ Practice pr = new Practice(); Person p = new Person("Abe", "Lincoln"); System.out.println(p);// reference printed System.out.println( p.getFirstName() + " " + p.getLastName()); pr.reverse(p);// just a swap System.out.println(p);// reference printed System.out.println( p.getFirstName() + " " + p.getLastName()); } // First and last name change places. void reverse(Person p){ String first = p.getFirstName(); p.setFirstName(p.getLastName()); p.setLastName(first); } output: Person@93dee9 Abe Lincoln Person@93dee9 Lincoln Abe So, this is pass- by-value, since the value of the reference is passed.

42 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 42 Passing Primitives This is essentially the same as the last case – we still pass-by-value and NOT pass-by-reference. There is no pass-by- reference in Java.

43 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 43 End of Chapter 3


Download ppt "Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 1 Sun Certified Java 1.4 Programmer Chapter 3 Notes Gary Lance"

Similar presentations


Ads by Google