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.

Slides:



Advertisements
Similar presentations
Strings in Java 1. strings in java are handled by two classes String &
Advertisements

Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Fundamental Programming Structures in Java: Strings.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Chapter 7: Characters, Strings, and the StringBuilder.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Object Oriented Programming Lecture 2: BallWorld.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings Chapter.
The Methods and What You Need to Know for the AP Exam
CompSci 230 S Programming Techniques
Information and Computer Sciences University of Hawaii, Manoa
Strings.
String and String Buffers
String Handling in JAVA
Java Review: Reference Types
Primitive Types Vs. Reference Types, Strings, Enumerations
EE422C - Software Design and Implementation II
Modern Programming Tools And Techniques-I Lecture 11: String Handling
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

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() { 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 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);

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.

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

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. else 8. 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. else 8. System.out.println("pt1 is not equals pt2"); 9. } What is the output of the above program? Equals Operator (==)

1. class Point2D 2. { 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 Point2D 2. { 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 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 +=

Example What is returned by the following? “this” + “that” “alpha” + 3 “alpha” “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(“ "); 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”; 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 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()

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);

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 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];

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

Multidimensional Arrays Declaration Syntax: type [] [] identifier; Allocation specify 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 here 5. // Add here 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,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 zero at 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 exception import java.util.*; // some other exception classes 1. class AException extends Exception 2. { 3. private String name; 4. public AException() 5. { 6. name = "My Exception"; 7. } 8. } 9. class Function 10. { 11. static void A1() 12. throws AException 13. { 14. throw new AException(); 15. } 16. } 17.

1. public class SimpleException 2. { 3. public static void main(String [] args) 4. { 5. try 6. { 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”);