1 / 39

Chapter 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 xx) { x = xx ;} public void setY(double yy) { y = yy ;} public double getX()

shasta
Download Presentation

Chapter 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 Reference Types

  2. Class : Point2D class 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); } }

  3. Objects and References • Objects and References Object – any non-primitive type ReferenceVariable – 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);

  4. Creating Objects Declaration Point2D pt2d; // null reference, uninitialized Truck t; Button b; Initialization/Allocation pt2d = new Point2D(2,2); // Now it is initialized t = 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.

  5. The dot (.) Operator Used for dereferencing Point2D pt2d = new Point2D(2,10); pt2d.setX(10); // send a message double xvalue ; xvalue = pt2d.getX();

  6. 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();

  7. Assignment ( = ) Primitive types – copies value Reference type – copies value (Address) If a and b are objects, then after the assignment a = 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.

  8. Point2D pt1 = new Point2D(1.0,10.0); Point2D pt2 = pt1 ; pt1.getX(); pt2.getX();

  9. Equals Operator (==) • public static void main(String [] args) • { • Point2D pt1 = new Point2D(1,0); • Point2D pt2 = new Point2D(1,0); • if ( pt1 == pt2 ) • System.out.println("pt1 == pt2"); • else • System.out.println("pt1 != pt2"); • } Q: How do you compare contents for reference types?

  10. Equals Operator (==) • public static void main(String [] args) • { • Point2D pt1 = new Point2D(1,0); • Point2D pt2 = new Point2D(1,0); • if ( pt1.equals(pt2) ) • System.out.println("pt1 is equals pt2"); • else • System.out.println("pt1 is not equals pt2"); • } What is the output of the above program?

  11. class Point2D • { • private double x,y; • public Point2D(double xx,double yy) • { x = xx ; y = yy ;} • ……………………… • public void show() • { • System.out.println(“x-value = “+x); • System.out.println(“y-value = “+y); • } • public boolean equals(Object obj) • { • Point2D pt = (Point2D)obj; • boolean rvalue = true ; • if ( x != pt.x || y != pt.y ) return false; • return rvalue ; • } • }

  12. class Point2D • { • private double x,y; • public Point2D(double xx,double yy) • { x = xx ; y = yy ;} • ……………………… • public void show() • { • System.out.println(“x-value = “+x); • System.out.println(“y-value = “+y); • } • public boolean equals(Object obj) • { • Point2D pt ; • if( obj instanceof Point2D ) pt = (Point2D)obj; • boolean rvalue = true ; • if ( x != pt.x || y != pt.y ) return false; • return rvalue ; • } • }

  13. Strings Predefined Behaves almost like an object Strings are immutable. That is, once a string object is constructed, its contents may not change. Operators invoke methods + , concatenation +=

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

  15. String/StringBuffer • Strings are immutable, but StringBuffers are mutable. • StringBuffer sbuffer1 = new StringBuffer(); • System.out.println("ouput 1 = "+sbuffer1); • sbuffer1.append(“1234567890"); • System.out.println("ouput 2 = "+sbuffer1); • sbuffer1.append(12.0); • System.out.println("ouput 3 = "+sbuffer1); • sbuffer1.replace(8,9,"2"); • System.out.println("ouput 4 = "+sbuffer1); • sbuffer1.insert(7,"A"); • System.out.println("ouput 5 = "+sbuffer1);

  16. String Methods toUppercase(), toLowercase(), length(), trim() concat(), substring(), indexOf() • String x = “LifeIsWonderful”; • char ch = x.charAt(5); • String sub1 = x.substring(4,6); • String sub2 = x.substring(6); • String sub3 = sub2.concat(sub1); • int j = x.indexOf(‘e’); • System.out.println("LifeisWonderFul ".length()); • System.out.println("LifeisWonderFul ".trim().length());

  17. 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”);

  18. String Comparison equals method compareTo 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()

  19. Type Conversions • From String to integer/double/float Integer.parseInt(“100”); Double.parseDouble(“10.5”); Float.parseFloat(“10.5”); • From integer/double/float to String String str1 = String.valueOf(10.0);

  20. 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()); • }

  21. 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()); • }

  22. 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

  23. Array • Array Declaration type[] identifier; type identifier[]; int [] a; int a []; • Array Allocation keyword new must provide constant size identifier = new type[size]; a = new int [6];

  24. Array • 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};

  25. 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 arguments public static void main(String [] args) { System.out.println(“variable 1 = “ + args[0]); System.out.println(“variable 2 = “ + args[1]); }

  26. Multidimensional Arrays • Declaration Syntax: type [] [] identifier; • Allocation specify size of each dimension int [] [] table; table = new int [5] [6]; // two dimensional array

  27. Array Passing: 1D • public static void main(String []args) • { • int [] array1 = {1,2,3,4,5,6,7,8,9,10}; • int totalSum = sum(array1); • System.out.println(totalSum); • } • public static int sum(int inarray[]) • { • int rvalue=0; • for(int i=0 ; i<inarray.length ;i++) • rvalue = rvalue +inarray[i]; • return rvalue ; • }

  28. Array Passing: 2D • public static void main(String []args) • { • int [][] array2 = {{1,2,3,4,5},{6,7,8,9,10}}; • // Add here • // Add here • System.out.println(totalSum); • } • public static int sum(int inarray[]) • { • int rvalue=0; • for(int i=0 ; i<inarray.length ;i++) • rvalue = rvalue +inarray[i]; • return rvalue ; • }

  29. Array Passing: 2D • public static void main(String []args) • { • int [][]array2 = {{1,2,3,4,5},{6,7,8,9,10}}; • int totalSum = sum(array2[0]); • totalSum = totalSum + sum(array2[1]); • System.out.println(totalSum); • } • public static int sum(int inarray[]) • { • int rvalue=0; • for(int i=0 ; i<inarray.length ;i++) • rvalue = rvalue +inarray[i]; • return rvalue ; • }

  30. Array Passing: 2D • public static void main(String []args) • { • int [][]array2 = {{1,2,3,4,5},{6,7,8,9}}; • System.out.println(sum2d(array2)); • } • public static int sum2d(int inarray[][]) • { • int value=0 ; • for(int i=0 ; i<inarray.length ;i++) • for(int j=0 ; j< inarray[i].length ; j++ ) • value = value + inarray[i][j] ; • return value ; • }

  31. Input and Output The java.io package Predefined objects: System.in System.out System.err

  32. 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.

  33. 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

  34. Unchecked Exception • Error • Runtime Exception • ArithmeticException • NumberFormatException • IndexOutOfBoundsException • NegativeArraySizeException • NullPointerException

  35. Exception Examples • public static void main(String [] args) • { • System.out.println(1/0); • } java.lang.ArithmeticException: / by zero at simpleexception.SimpleException.main (SimpleException.java:36) Exception in thread "main"

  36. Q. What is the output of the following program? • public static void main(String [] args) • { • System.out.println(1.0/0); • }

  37. import java.io.IOException; // most typical checked exception import java.util.*; // some other exception classes • class AException extends Exception • { • private String name; • public AException() • { • name = "My Exception"; • } • } • class Function • { • static void A1() • throws AException • { • throw new AException(); • } • }

  38. public class SimpleException • { • public static void main(String [] args) • { • try • { • Function.A1(); • } • catch(AException e) • { • System.out.println("Hello"); • } • catch(Exception e) • { • System.out.println("Exception Caught"); • } • } • }

  39. 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”);

More Related