Title: Kickstart Intro to Java Part II
1Kickstart Intro to JavaPart II
- COMP346/5461 - Operating Systems
- Revision 1.5
- July 23, 2003
2Topics
- Arrays
- Basics of Inheritance in Java
- Threads Scheduling
- Exception Handling
- Examples
3Creating Arrays
- Two ways
- Using newint aMyIntArray new int10
- NOTE creating an array does not imply creating
objects for the elements of the array! Objects
must be explicitly created! - In our case, we have a primitive data type int,
so it gets initialized to 0, in case of an object
it is null. - Using initializerint aMyIntArray
1,2,3,4,5,6,7,8,9,10 - This creates an array dynamically and initializes
it with the values. - NOTE this is different from C/C because values
in the initializer in Java can be dynamic,
whereas in C/C they are always constant.
4Anonymous Arrays and Objects
- Anonymous arrays dont have a name and can be
created dynamically within the initializer - Same way any allocated objects can be anonymous.
- In C/C that would be a memory leak.
countArgs( new String Bar, Ban, Ech )
5Multidimensional Arrays
- Implemented as arrays-of-arrays, so arrays arent
necessarily rectangular. - Syntaxbyte a64bytes new byte88
- No need to specify all dimensions right awayint
aCube new int7 - Basically, we have 7 arrays of type int.
- Later on the new dimensions will be there after
proper initialization. - This is illegal, howeverint aCube new
int52 - Example TriangleArray.java
6Triangle Array Example Explained
- After we execute this linefloat aTriangle
new float7we have the following
where a dot () stands for null
0
1
2
3
4
5
6
7Triangle Array Example Explained (2)
- Then, gradually, with every iteration, the array
becomes multiple-dimensioned
0 1 2 3 4 5 6
0
1
2
3
4
5
6
0.0 X 1.02.0 2.03.04.0 3.04.05.0
6.0 4.05.06.07.08.0 5.06.07.08
.09.010.0 6.07.08.09.010.011.012
.0
8Accessing Array Elements
- Just like in C/C
- If an attempt is made to access the array outside
boundaries, an exception ArrayIndexOutOfBoundsExce
ption is thrown, and can be caught and dealt with
during run-time. - More about exceptions later in the tutorial.
9Basics of Inheritance in Java
- No multiple inheritance.
- class Foo extends Bar means Foo inherits Bar.
- If no extends given, then the object is always
assumed to inherit from the Object class. - By using super() in the childs class we can call
parents constructor.
10Threads Scheduling
- Recall from COMP229 what threads are
- One parent process, thus code and resources are
the same. - Own stack and registers state, perhaps some
private data. - Java is a multithreaded language and has a very
easy to use thread package (java.lang.Thread
class) unlike C/C - JVM 1.2. and earlier use priority-based
scheduling and a Round Robin policy for the
threads of the same priority. Later versions of
the JVM let the OS schedule the threads (which is
particularly useful on multiple CPUs)
11java.lang.Thread
- This class provides facilities to start and stop
threads, assign priorities, etc.http//java.sun.c
om/products/jdk/1.2/docs/api/java/lang/Thread.html
- Theres a built-in support for the synchronized
methods and blocks of code using the synchronized
keyword. This means only one thread at a time
should run the code marked as synchronized.
12Most Often Used Method of the Thread class (1)
- start()When you create an object of a subclass
Thread it doesnt do anything useful, just wastes
space. In order for the created thread to begin
execution and do some useful work, the parent
thread has to invoke the start() method. - run()Upon call to start() by the parent, the
created thread starts execution the body of the
run() method, which is provided by the user in
the subclassed thread object.
13Most Often Used Method of the Thread Class (2)
- yield()Among the threads of the same priority,
if one thread wishes voluntarily relinquish the
CPU and let another thread go ahead, it calls
yield(). Using yield() instruction in any form is
sometimes called cooperative scheduling. We might
use it to simulate a some sort of an interrupt
at a given point of the threads execution path. - join()An analogy to the wait() system call in C.
A parent thread calls join() on a child thread
object if it wants to pause and wait until the
child terminates.
14Threads Example
- Debrief threads operate on the common stack
concurrently. Concurrency implies atomicity
otherwise, we get unexpected results. - Pseudo codeacquire block block stacktop
(!) top--release block top (!) stacktop
block - Block.java explained
15Another Way of Creating Threads
- is to implement interface Runnable.
- When is it needed? Just when you need a Thread
behaviour, but you cannot subclass Thread because
your object already extends from something. - Syntax class myClass extends OtherClass
implements Runnable - You will need to define run() with no arguments
of that class. - Then do
- Thread myObj new myClass()
- myObj.start()
16Javas Exception Handling Mechanism
- A very significant feature of Java. Beware It is
similar in a way to that of C, but not the
same! - Some terminology
- Exception is a signal indicating that something
exceptional happened (whatever exceptional
means), usually an error. - Throwing an exception means signaling that
exceptional condition. - Catching an exception is to react to the signal
an do whatever necessary to recover from it (i.e.
to handle an exception).
17Exception Propagation
- Lexical block structure of Java method first
- Up the method call stack
- Next higher enclosing code block
-
- Invoking method
- If never caught to main() gt JVM exits with an
error message and a stack trace.
18Advantages of Using Exceptions
- Logical way of dealing with regular exceptions
and errors by grouping the handling code in one
place. - Clarity of algorithms and code in your programs.
- Less error-prone code (sometimes catching an
exception is mandatory and enforced by Java).
19Exception Objects
- All Exceptions are derived from the class
Throwable (java.lang.Throwable), which has two
standard subclasses - Error (usually fatal exceptions, which should
not/cannot be caught, e.g. out of memory,
linkage, dyn. loading, etc) - Exception (usually recoverable, file ops, array
bounds, etc) - The Exceptions are also Objects thus have some
methods and data members. E.g. getMessage()
returns a human-readable error that occurred.
20Handling Exceptions
- Three statements try / catch / finally
- try ...Does nothing but indicates a block of
code which is more likely to have exceptions. - catch(Exception e) ...try is followed by zero
or more catch statements to handle specified
exceptions - finally ...catch is optionally followed by one
finally block, which does clean up and is always
guaranteed to execute regardless how the try and
catch blocks exit (only System.exit() is not
part of that rule).
21Declaring Exceptions
- To throw normal exceptionspublic void
writeFile() throws IOException public void
break_window() throws BrokenWindowException - Normal means not subclasses of either Error or
RuntimeException - C diff Java uses throws and not throw
22Defining and Generating Exceptions
- throw new MyException(oh dear)
- The application stops and looks for catch
statements if not found, it propagates the
exception to higher levels as described before. - ExceptionExample.java
23Links and References
- Official Java site http//java.sun.com
- Java in a Nutshell, Second Edition by David
Flanagan, (C) 1997 OReily Associates, Inc.
ISBN 1-56592-262-X