Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double...

39
Chapter 2 Reference Types

description

Objects and References Object – any non-primitive type Reference Variable – a variable that stores the memory address where an object is resides null reference – the “empty” reference, that is, it is not currently referencing any object. Example new Point2D(2,2); // New object. Q: How are we going to use this new object? A: Use reference: Point2D mypoint = new Point2D(2,2);

Transcript of Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double...

Page 1: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Chapter 2

Reference Types

Page 2: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Class : Point2Dclass Point2D{ private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double xx) { x = xx ;} public void setY(double yy) { y = yy ;} public double getX() { return x;} public double getY() { return y;} public void show() { System.out.println(“x-value = “+x); System.out.println(“y-value = “+y); }}

Page 3: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Objects and References

Objects and ReferencesObject – any non-primitive typeReference Variable – a variable that stores the memory address where an

object is residesnull reference – the “empty” reference, that is, it is not currently referencing

any object.

Example new Point2D(2,2); // New object.

Q: How are we going to use this new object?A: Use reference: Point2D mypoint = new Point2D(2,2);

Page 4: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Creating Objects

Declaration Point2D pt2d; // null reference, uninitialized

Truck t; Button b;

Initialization/Allocation

pt2d = new Point2D(2,2); // Now it is initializedt = new Truck();b = new Button();

Garbage collection When a constructed object is no longer referenced by any object, the memory it consumes will automatically be reclaimed. This technique is known as garbage collection.

Page 5: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

The dot (.) Operator

Used for dereferencing

Point2D pt2d = new Point2D(2,10);pt2d.setX(10); // send a message

double xvalue ; xvalue = pt2d.getX();

Page 6: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Class Point2D Expanded

class Point2D{ private double x,y; public Point2D(double xx,double yy) ………………………….

public Point2D getOrigin() { return Point2D(0,0);}}

Point2D pt2d = new Point2D(10,10);double xx = Pt2d.getOrigin().getX();

Page 7: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Assignment ( = )

Primitive types – copies valueReference type – copies value (Address)

If a and b are objects, then after the assignmenta = b

both a and b point to the same object. That is, a and b are now alias of each other because they are two names that refer to the same object.

Page 8: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Point2D pt1 = new Point2D(1.0,10.0);Point2D pt2 = pt1 ;

pt1.getX();pt2.getX();

Page 9: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Equals Operator (==)

1. public static void main(String [] args)2. {3. Point2D pt1 = new Point2D(1,0);4. Point2D pt2 = new Point2D(1,0);

5. if ( pt1 == pt2 )6. System.out.println("pt1 == pt2");7. else8. System.out.println("pt1 != pt2");9. }

Q: How do you compare contents for reference types?

Page 10: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

1. public static void main(String [] args)2. {3. Point2D pt1 = new Point2D(1,0);4. Point2D pt2 = new Point2D(1,0);

5. if ( pt1.equals(pt2) )6. System.out.println("pt1 is equals pt2");7. else8. System.out.println("pt1 is not equals pt2");9. }

What is the output of the above program?

Equals Operator (==)

Page 11: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

1. class Point2D2. {3. private double x,y;4. public Point2D(double xx,double yy)5. { x = xx ; y = yy ;}6. ………………………7. public void show()8. {9. System.out.println(“x-value = “+x);10. System.out.println(“y-value = “+y);11. }12. public boolean equals(Object obj)13. {14. Point2D pt = (Point2D)obj;15. boolean rvalue = true ;16. if ( x != pt.x || y != pt.y ) return false;17. return rvalue ;18. }19. }

Page 12: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

1. class Point2D2. {3. private double x,y;4. public Point2D(double xx,double yy)5. { x = xx ; y = yy ;}6. ………………………7. public void show()8. {9. System.out.println(“x-value = “+x);10. System.out.println(“y-value = “+y);11. }12. public boolean equals(Object obj)13. {14. Point2D pt ;15. if( obj instanceof Point2D ) pt = (Point2D)obj;16. boolean rvalue = true ;17. if ( x != pt.x || y != pt.y ) return false;18. return rvalue ;19. }20. }

Page 13: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Strings

PredefinedBehaves almost like an objectStrings are immutable. That is, once a

string object is constructed, its contents may not change.

Operators invoke methods + , concatenation +=

Page 14: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Example

What is returned by the following?“this” + “that”“alpha” + 3 “alpha” + 3 + 1

3 + 1 + “alpha”

Page 15: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

String/StringBuffer Strings are immutable, but StringBuffers are mutable.

1. StringBuffer sbuffer1 = new StringBuffer();2. System.out.println("ouput 1 = "+sbuffer1);

1. sbuffer1.append(“1234567890");2. System.out.println("ouput 2 = "+sbuffer1);

1. sbuffer1.append(12.0);2. System.out.println("ouput 3 = "+sbuffer1);

1. sbuffer1.replace(8,9,"2");2. System.out.println("ouput 4 = "+sbuffer1);

1. sbuffer1.insert(7,"A");2. System.out.println("ouput 5 = "+sbuffer1);

Page 16: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

String Methods

toUppercase(), toLowercase(), length(), trim()concat(), substring(), indexOf()

1. String x = “LifeIsWonderful”;2. 3. char ch = x.charAt(5);4. String sub1 = x.substring(4,6);5. String sub2 = x.substring(6);6. String sub3 = sub2.concat(sub1);7. int j = x.indexOf(‘e’);

8. System.out.println("LifeisWonderFul ".length());9. System.out.println("LifeisWonderFul ".trim().length());

Page 17: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

String equals and ==

String s1 = new String(“Hello”);String s2 = new String(“Hello”);String s3 = “Hello”;String s4 = “Hello”;

if (s1.equals(s2)) System.out.println(“A”);if (s3.equals(s4)) System.out.println(“B”);

if ( s1==s2 ) System.out.println(“C”);if ( s3==s4 ) System.out.println(“D”);

Page 18: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

String Comparison

equals methodcompareTo method str1.compareTo(str2)

=0 if the argument string is equal to this string; <0 if this str1 is lexicographically less than str2

“H”.compareTo(“h”);“Hello”.compareTo(“HelloWorld”);

>0 if this str1 is lexicographically greater than str2

this.charAt(k)-anotherString.charAt(k) this.length()-anotherString.length()

Page 19: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Type Conversions

From String to integer/double/floatInteger.parseInt(“100”);Double.parseDouble(“10.5”);Float.parseFloat(“10.5”);

From integer/double/float to StringString str1 = String.valueOf(10.0);

Page 20: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

StringTokenizer I

StringTokenizer is a legacy class that is retained for compatibility reasons. Its use is discouraged.

import java.util.StringTokenizer

StringTokenizer st = new StringTokenizer("this is a : test");

int n= st.countTokens() ; System.out.println(“Token Numbers = “+n); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }

Page 21: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

StringTokenizer II

import java.util.StringTokenizer

StringTokenizer st = new StringTokenizer("this is a : test“, ”:”);

int n= st.countTokens() ; System.out.println(“Token Numbers = “+n); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }

Page 22: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Arrays

An array is a collection of identically typed entities

Declared with a fixed number of cells Each cell holds one data item Each cell has its own address called its index Random access – you can jump to any cell without

looking at the others

NOT a primitive type in Java

Page 23: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Array

Array Declarationtype[] identifier;

type identifier[];

int [] a; int a [];

Array Allocation keyword new must provide constant size

identifier = new type[size]; a = new int [6];

Page 24: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Array Initialization

Method 1

int [] iarray = new iarray[10];for( int i=0 ; i<iarray.length ; i++)

iarray[i] = 1;

Method 2

int [] iarray = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

Array

Page 25: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

More on Arrays

Index starts with 0

Given int [] iarray = {1, 2,3,4,5,6};What is the output for the followings?

System.out.println(iarray[0]);System.out.println(iarray[1]);System.out.println(iarray[6]);

Command line argumentspublic static void main(String [] args){ System.out.println(“variable 1 = “ + args[0]);

System.out.println(“variable 2 = “ + args[1]);}

Page 26: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Multidimensional Arrays

DeclarationSyntax: type [] [] identifier;

Allocationspecify size of each dimension

int [] [] table; table = new int [5] [6]; // two dimensional array

Page 27: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Array Passing: 1D

1. public static void main(String []args)2. {3. int [] array1 = {1,2,3,4,5,6,7,8,9,10};4. int totalSum = sum(array1);5. System.out.println(totalSum);6. }

7. public static int sum(int inarray[])8. {9. int rvalue=0;

10. for(int i=0 ; i<inarray.length ;i++)11. rvalue = rvalue +inarray[i];

12. return rvalue ;13. }

Page 28: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

1. public static void main(String []args)2. {3. int [][] array2 = {{1,2,3,4,5},{6,7,8,9,10}};4. // Add here5. // Add here6. System.out.println(totalSum);7. }

8. public static int sum(int inarray[])9. {10. int rvalue=0;

11. for(int i=0 ; i<inarray.length ;i++)12. rvalue = rvalue +inarray[i];

13. return rvalue ;14. }

Array Passing: 2D

Page 29: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

1. public static void main(String []args)2. {3. int [][]array2 = {{1,2,3,4,5},{6,7,8,9,10}};4. int totalSum = sum(array2[0]);5. totalSum = totalSum + sum(array2[1]);6. System.out.println(totalSum);7. }

8. public static int sum(int inarray[])9. {10. int rvalue=0;11. for(int i=0 ; i<inarray.length ;i++)12. rvalue = rvalue +inarray[i];13. return rvalue ;14. }

Array Passing: 2D

Page 30: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

1. public static void main(String []args)2. {3. int [][]array2 = {{1,2,3,4,5},{6,7,8,9}};4. System.out.println(sum2d(array2));5. }

6. public static int sum2d(int inarray[][])7. {8. int value=0 ;9. for(int i=0 ; i<inarray.length ;i++)10. for(int j=0 ; j< inarray[i].length ; j++ )11. value = value + inarray[i][j] ;12. return value ;13. }

Array Passing: 2D

Page 31: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Input and Output

The java.io package

Predefined objects: System.in System.out System.err

Page 32: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Exception Handling

Exceptions objects that store information and are transmitted outside the normal return sequence. They are propagated through the calling sequence until some routine catches the exception. Then the information stored in the object can be extracted to provide error handling.

Exception

Checked Exception Unchecked Exception

Page 33: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Common Exceptions

Standard exceptions in Java are divided into two categories:

unchecked exception if not caught, it will propagate to the main and

will cause an abnormal program termination checked exception

must be caught by the use of the try/catch block or explicitly indicate that the exception is to be propagated by the use of a throws clause in the method declaration

Page 34: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Unchecked Exception

Error

Runtime Exception ArithmeticException NumberFormatException IndexOutOfBoundsException NegativeArraySizeException NullPointerException

Page 35: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Exception Examples

1. public static void main(String [] args)2. {3. System.out.println(1/0);4. }

java.lang.ArithmeticException: / by zeroat simpleexception.SimpleException.main

(SimpleException.java:36)Exception in thread "main"

Page 36: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

Q. What is the output of the following program?

public static void main(String [] args) { System.out.println(1.0/0); }

Page 37: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

import java.io.IOException; // most typical checked exceptionimport java.util.*; // some other exception classes

1. class AException extends Exception2. {3. private String name;4. public AException()5. {6. name = "My Exception";7. }8. }

9. class Function10. {11. static void A1()12. throws AException13. {14. throw new AException();15. }16. }17.

Page 38: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

1. public class SimpleException2. {3. public static void main(String [] args)4. {5. try6. {7. Function.A1();8. }9. catch(AException e)10. {11. System.out.println("Hello");12. }13. catch(Exception e)14. {15. System.out.println("Exception Caught");16. }17. }18. }

Page 39: Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.

The throw and throws Clauses

The programmer can generate an exception by the use of the throw clause. For example, the following line of code creates and then throws an ArithmeticException object:

throw new ArithmeticException(“Divide by zero”);