Download Method 2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
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

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.
2.
3.
4.
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");
5.
6.
7.
8.
9.
}
Q: How do you compare contents for reference types?
Equals Operator (==)
1.
2.
3.
4.
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");
5.
6.
7.
8.
9.
}
What is the output of the above program?
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
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 ;
}
}
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” + 3 + 1
3 + 1 + “alpha”
String/StringBuffer

1.
2.
1.
2.
1.
2.
1.
2.
1.
2.
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);
String Methods
toUppercase(), toLowercase(), length(), trim()
concat(), substring(), indexOf()
1.
String x = “LifeIsWonderful”;
2.
3.
4.
5.
6.
7.
8.
9.
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());
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
<0
if the argument string is equal to this string;
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

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};
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.
2.
3.
4.
5.
6.
7.
8.
9.
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;
10.
11.
for(int i=0 ; i<inarray.length ;i++)
rvalue = rvalue +inarray[i];
12.
13.
return rvalue ;
}
Array Passing: 2D
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
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;
11.
12.
for(int i=0 ; i<inarray.length ;i++)
rvalue = rvalue +inarray[i];
13.
14.
return rvalue ;
}
Array Passing: 2D
1.
2.
3.
4.
5.
6.
7.
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 ;
14. }
8.
9.
10.
11.
12.
13.
Array Passing: 2D
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
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 ;
}
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.
2.
3.
4.
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"
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.
2.
3.
4.
5.
6.
7.
8.
class AException extends Exception
{
private String name;
public AException()
{
name = "My Exception";
}
}
class Function
10. {
11. static void A1()
12.
throws AException
13. {
14.
throw new AException();
15. }
16. }
9.
17.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
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");
}
}
}
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”);
Related documents