Arrays
• In Java, arrays are objects.
• Like all objects in Java, you can only point to them.
• Unlike a C++ array variable, which is treated like a
pointer to the first element of the array, a Java array
variable points to the whole object.
• There is no way to point to a particular slot in an array.
C 2008-17 Imran A. Zualkernan 33
Array Declarations
int[] arrayOne;
an array of
of int is a pointer to
arrayOne null
C 2008-17 Imran A. Zualkernan 34
Example
int[] arrayOne; // a pointer to an array object; initially null
int arrayTwo[]; // allowed for compatibility with C; don't use this!
arrayOne = new int[10]; // now arrayOne points to an array object
arrayOne[3] = 17; // accesses one of the slots in the array
arrayOne = new int[5]; // assigns a different array to arrayOne
// the old array is inaccessible (and so
// is garbage-collected)
[Link]([Link]); // prints 5
int[] alias = arrayOne; // arrayOne and alias share the same array object
// Careful! This could cause surprises
alias[3] = 17; // Changes an element of the array pointed to by
// alias, which is the same as arrayOne
[Link](arrayOne[3]); // prints 17
C 2008-17 Imran A. Zualkernan 35
Picture
C 2008-17 Imran A. Zualkernan 36
Strings
String s = "hello";
String t = "world";
[Link](s + ", " + t); // prints "hello, world"
[Link](s + "1234"); // "hello1234"
[Link](s + (12*100 + 34)); // "hello1234"
[Link](s + 12*100 + 34); // "hello120034" (why?)
[Link]("The value of x is " + x); // will work for any x
[Link]("[Link] = " + [Link]);
// "[Link] = [Link]@80455198"
String numbers = "";
for (int i=0; i<5; i++) {
numbers += " " + i; // correct but slow
}
[Link](numbers); // " 0 1 2 3 4"
class instance
C 2008-17 Imran A. Zualkernan 37
Object Class
• The Object class sits at the top of the Java class
hierarchy tree.
• Every class is a direct or indirect descendant of the
Object class.
• Every class you use or write inherits the instance
methods of Object.
C 2008-17 Imran A. Zualkernan 38
Object Class
• Every class (with one exception) has exactly one super
class (single inheritance) called Object.
• If you leave out the extends specification, Java treats it
like "extends Object".
• The primordial class Object is the lone exception -- it
does not extend anything.
• All other classes extend Object either directly or
indirectly.
• Object has a method toString, so every class has a
method toString; either it inherits the method from its
super class or it overrides it.
C 2008-17 Imran A. Zualkernan 39
Constructors
• If a constructor has arguments, you supply corresponding values when
using new.
• Even if it has no arguments, you still need the parentheses (unlike C++).
• There can be multiple constructors, with different numbers or types of
arguments. This is called constructor overloading.
• Default constructor is created only if there are no constructors. If you
define any constructor for your class, no default constructor is automatically
created.
• this(...) - Calls another constructor in same class.
• super(...). Use super to call a constructor in a parent class.
• The Java compiler inserts a call to the parent constructor (super) if you don't
have a constructor call as the first statement of you constructor.
• Unlike C++, you cannot overload operators.
C 2008-17 Imran A. Zualkernan 40
Example – constructors
class Pair { In C++
int x, y; this->x;
Pair(int u, int v) {
x = u; // the same as this.x = u
y = v;
}
Pair(int x) {
this.x = x; // not the same as x = x!
y = 0;
}
Pair() {
x = 0;
y = 0;
}
}
C 2008-17 Imran A. Zualkernan 41
Example - constructors
class Test {
public static void main(String[] argv) {
Pair p1 = new Pair(3,4);
Pair p2 = new Pair(); // same as new Pair(0,0)
Pair p3 = new Pair; // error! need to say Pair()
}
}
C 2008-17 Imran A. Zualkernan 42
Method Inheritance
• Method inheritance is specified with the keyword
extends. (similar to inheritance in C++)
class Base {
int f() { /* ... */ }
void g(int x) { /* ... */ }
}
class Derived extends Base {
void g(int x) { /* ... */ }
double h() { /* ... */ }
}
C 2008-17 Imran A. Zualkernan 43
Method Inheritance
• Class Derived has three methods: f, g, and h.
• The method Derived.f() is implemented in the
same way (the same executable code) as
Base.f(), but Derived.g() overrides the
implementation of Base.g().
• We call Base the super class of Derived and
Derived a subclass of Base.
C 2008-17 Imran A. Zualkernan 44
Interface Inheritance
• Interface inheritance is specified with
implements.
• A class implements an Interface, which is
like a class, except that the methods don't
have bodies.
• This is almost like inheriting from a pure
abstract class in C++
C 2008-17 Imran A. Zualkernan 45
Example - Interface
• Animal
interface Animal {
public void eat();
public void travel();
}
Source: [Link]
C 2008-17 Imran A. Zualkernan 46
Difference between an Interface
and a Class
1. You cannot instantiate an interface.
2. An interface does not contain any constructors.
3. All of the methods in an interface are abstract.
4. An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final.
5. An interface is not extended by a class; it is implemented by a
class.
6. An interface can extend multiple interfaces.
Source: [Link]
C 2008-17 Imran A. Zualkernan 47
Another Example - Interface
• Built-in interfaces Runnable and Enumeration.
interface Runnable {
Things that are runnable
void run();
}
interface Enumeration { Things that can be enumerated
Object nextElement();
boolean hasMoreElements();
}
C 2008-17 Imran A. Zualkernan 48
Example – Interfaces and Inheritance
class Words extends StringTokenizer implements Enumeration, Runnable {
public void run() {
for (;;) {
String s = nextToken();
if (s == null) {
return;
}
[Link](s);
}
}
Words(String s) { Calls constructor for StringTokenizer
super(s); with an argument (s).
// perhaps do something else with s as well
}
}
C 2008-17 Imran A. Zualkernan 49
Example
• The class Words needs methods run,
hasMoreElements, and nextElement to meet its promise
to implement interfaces Runnable and Enumeration.
• The class Words inherits implementations of
hasMoreElements and nextElement from
StringTokenizer , but it has to provide its own
implementation of run.
C 2008-17 Imran A. Zualkernan 50
Casting
double pi = [Link];
int three = (int) pi; // throws away the fraction
C 2008-17 Imran A. Zualkernan 51
Casting
• A cast can also be used to convert an
object reference to a super class or
subclass.
• For example,
Words w = new Words("this is a test");
Object o = [Link]();
String s = (String) o;
[Link]("The first word has length " + [Link]());
C 2008-17 Imran A. Zualkernan 52
Casting
• If you are not sure of the type of an object,
you can test it with instanceof (note the
lower case "o"), or find out more about it
with the method [Link]()
if (o instanceof String) {
n = ((String) o).length();
} else {
[Link]("Bad type " + [Link]().getName());
}
C 2008-17 Imran A. Zualkernan 53
Exceptions
class Example1 {
public static void main(String args[]) { throw an instance
of an exception
try {
// Try block to handle code that may cause exception
throw new Exception(“foo”);
[Link]("Try block message");
} catch (ArithmeticException e) {
Catch a class
// This block is to catch divide-by-zero error
[Link]("Error: Don't divide a number by zero");
}
[Link]("I'm out of try-catch block in Java.");
}
}
C 2008-17 Imran A. Zualkernan 54
Exception Handling
C 2008-17 Imran A. Zualkernan 55
Exception Types
Source:[Link]
C 2008-17 Imran A. Zualkernan 56
Exception Types
• Checked exceptions are exceptions that
must be declared in the throws clause of a
method. A checked exception indicates an
expected problem that can occur during
normal system operation.
• Unchecked exceptions are exceptions
that do not need to be declared in a throws
clause. The most common example is a
NullPointerException.
C 2008-17 Imran A. Zualkernan 57
Input
BufferedReader input =
new BufferedReader(new
InputStreamReader([Link]));
for(;;) {
String line = [Link]();
if (line == null) {
break;
}
// do something with the next line
}
C 2008-17 Imran A. Zualkernan 58
Input from File
BufferedReader input =
new BufferedReader(new
FileReader("somefile"));
for (;;) {
String line = [Link]();
if (line == null) {
break;
}
// do something with the next line
}
C 2008-17 Imran A. Zualkernan 59