Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double...
-
Upload
bethanie-barnett -
Category
Documents
-
view
237 -
download
0
description
Transcript of Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double...
Chapter 2
Reference Types
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); }}
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);
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.
The dot (.) Operator
Used for dereferencing
Point2D pt2d = new Point2D(2,10);pt2d.setX(10); // send a message
double xvalue ; xvalue = pt2d.getX();
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();
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.
Point2D pt1 = new Point2D(1.0,10.0);Point2D pt2 = pt1 ;
pt1.getX();pt2.getX();
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?
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 (==)
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. }
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. }
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 +=
Example
What is returned by the following?“this” + “that”“alpha” + 3 “alpha” + 3 + 1
3 + 1 + “alpha”
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);
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());
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”);
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()
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);
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()); }
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()); }
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
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];
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
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]);}
Multidimensional Arrays
DeclarationSyntax: type [] [] identifier;
Allocationspecify size of each dimension
int [] [] table; table = new int [5] [6]; // two dimensional array
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. }
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
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
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
Input and Output
The java.io package
Predefined objects: System.in System.out System.err
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
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
Unchecked Exception
Error
Runtime Exception ArithmeticException NumberFormatException IndexOutOfBoundsException NegativeArraySizeException NullPointerException
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"
Q. What is the output of the following program?
public static void main(String [] args) { System.out.println(1.0/0); }
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.
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. }
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”);