610 likes | 613 Views
JAVA. Developed at SUN by James Gosling with support from Bill Joy Net-based language Descended from Oak platform independent object oriented small The Java Tutorial: http://java.sun.com/docs/books/tutorial. Goals for Java. Simple easy to learn based on C/C++ small Object oriented
E N D
JAVA • Developed at SUN by James Gosling with support from Bill Joy • Net-based language • Descended from Oak • platform independent • object oriented • small • The Java Tutorial:http://java.sun.com/docs/books/tutorial
Goals for Java • Simple • easy to learn • based on C/C++ • small • Object oriented • single inheritance • Distributed • libraries supply protocols • Robust • strongly typed • safe pointer model • Secure • Platform independent • virtual machine • Portable • no implementation dependent data types
Goals for Java (cont.) • Compiled and interpreted • Multithreaded • Dynamic
Java Virtual Machine • Compiler translates Java into J-code • Stack-based virtual machine (JVM) • No undefined or platform specific data types • Other languages can be translated to J-code • Interpreter is lightweight, easy to implement • use widely available language, like C • J-code is highly optimized • J-code can be compiled on the fly
The JVM may be an interpreter an applet viewer a web browser part of an OS Classes could be loaded from filesystem or over a network JVMs use an environment variable, CLASSPATH, to find byte code (.class files) to execute J-code (JVM byte codes) Other classes How it Works Java compiler (javac) Java source Native code e.g., AWT Java interpreter (a JVM) Platform dependent Platform independent
Java combines benefits of • A strongly typed, OO language • Flexibility of an interpreted language • Lisp, Perl, Tcl • A smalltalk virtual machine with security protection • Java byte code verifier reduces runtime checks • Package structure for organizing classes into subsystems
Other benefits of Java • Exception handling • Support for multi-threading • Based on Hoare’s monitors • Highly optimized • Easy debugging • make debugging statements dependent on a constant value, which programmer sets when done debugging • compiler automatically removes unexecutable statements
Three levels of Security • Security manager • controls access to system resources • highlight windows of untrusted applications • Class loader • restricts classes loaded from network to interact with classes from the same location • Verifier • checks that incoming classes can’t forge pointers, violate access permissions, over/under flow operator stack, etc. • ensures type safety
Java doesn’t have • Macros and preprocessor • mostly used for platform dependencies • Operator overloading, except for + • (Very many) automatic type coercions • Pointer arithmetic • references are a higher level type and can only point to class objects, not to class methods • Explicit memory management • provides automatic garbage collection
Java and the Web • A web browser can incorporate a JVM and run Java applets as executable code • Life of an applet • Loaded by a web browser and asked to initialize itself • Informed each time it is displayed and hidden • Informed when it is no longer needed • Security manager prevents applet from accessing system resources or interacting with outside applications
Java classes • Class is the basic computation unit • encapsulates data and associated operations • found and loaded dynamically as needed • 22 architecture specific classes: “gateway to the real world” • networking, windowing, filesystem, etc. • Rest of Java is written in Java
Inheritance in Java • Single inheritance hierarchy • Multiple inheritance of interfaces • Interface specifies the operations but not the implementations • A class can “implement” multiple interfaces
Java coding conventions • Class names begin with upper case letters • Variables and method names begin with lower case letters • Constants are all upper case • Separate words with uppercase letter instead of underscores e.g. aVariableName AClassName aMethodName ACONSTANT
Classes in Java • Define an abstract data type • operations called methods • data called variables or fields • Many class instances or objects can exist • each instance may have a different state • e.g., different values for variables • all instances have the same methods • Arranged in a hierarchy • each class has a unique superclass (parent) • subclass (child) can add or modify methods or variables of the superclass
Variables in Java • Maintain state of a class instance • Belong to some class or class instance • static variable -- one per class • instance variable -- one per class instance • All variable values are by reference • point to their values, which are maintained on a heap • Initial value is null • access to null value raises the NullPointerException exception
A simple Java applet import java.applet.Applet; import java.awt.Graphics; public class Simple extends Applet { StringBuffer buffer; public void init( ) { buffer = new StringBuffer( ); addItem(“initializing …”); } public void start( ) { addItem(“starting …”); }
A simple Java applet (cont.) public void stop( ) { addItem(“stopping …”); } public void destroy( ) { addItem(“starting …”); } public void addItem(String newWord ) { System.out.println(newWord); buffer.append(newWord); repaint( ); }
A simple Java applet (cont.) public void paint (Graphics g) { //Draw a rectangle around the applet’s display area g.drawRectangle(0, 0, size( ).width-1, size( ).height-1); //Draw the current string inside the rectangle g.drawString(buffer.toString( ), 5, 15); } }
Lifetime of an Applet leave page/stop( ) iconify/stop( ) quit/destroy( ) load/init( );start( ); running stopped de-iconify/start( ) return to page/start( ) reload/stop( ); destroy( ); init( )
Part of the Java Class Hierarchy Object Component Button Container Window Panel Applet Simple
Subclassing and Inheritance • A subclass extends, refines, or specializes a superclass • A subclass can extend only one superclass • A subclass inherits the public methods and variables from its superclass • Does not inherit private members (in Java) • The subclass is considered a subtype of the superclass • All visible superclass operations apply to subclass
Subclassing Example Container Container( ) add(Component) doLayout( ) getComponent(int) paint(Graphics) print(Graphics) remove(Component) . . . Panel Window Panel( ) Panel(Layout) addNotify( ) Simple Applet getImage(URL, String) getParameter(String) play(URL) . . . Applet( ) init( ) start( ) . . . init( ) start( ) stop( ) destroy ( ) paint (Graphics)
Interfaces in Java • An interface class describes a protocol of behavior • Members are constants and abstract methods • Abstract methods have no implementations • Can be implemented by any class anywhere in the class heirarchy • Cannot be instantiated • Implementing classes agree to implement all methods declared in the interface • Class can implement multiple interfaces • Interface can be implemented by multiple classes • Does not force a class relationship
Interface Example • Objects can register themselves with an AlarmClock object to be woken up after some specified time • Objects call the letMeSleepFor method: public synchronized boolean letMeSleepFor( Sleeper theSleeper, long time) { int index = findNextSlot ( ); if (index == NOROOM) { return false; } else { sleepers[ index ] = theSleeper; sleepFor[ index ] = time; new AlarmThread( index ).start( ); return true; } }
Interface Example (cont.) • An object that wants to use AlarmClock must implement the wakeUp method • This is enforced by the type of theSleeper Public interface Sleeper { public void wakeUp ( ); public long ONE_SECOND = 1000; // in milliseconds public long ONE_MINUTE = 60000; // in milliseconds }
Interface Example (cont.) • Any object that implements this interface can be passed to letMeSleepFor Class GUIClock extends Applet implements Sleeper { . . . public void wakeUp ( ) { repaint ( ); clock.letMeSleepFor( this, ONE_MINUTE); } } • GUIClock updates its display every minute (showing the current time)
Abstract class v.s. Interface class • Why not use an abstract class for Sleeper? Abstract class Sleeper { public abstract void wakeUp ( ); } • Only objects that are subclasses of Sleeper would be able to use AlarmClock • Conceptually, AlarmClock should not force a class relationship on its users
Exceptional Conditions • Handling exceptional conditions can more than double the size of the code • Systems can respond to errors in many ways • crash • give error message and crash • give error message and let user retry • minimize work that must be redone • allow user to decide how much work must be redone • correct the error • allow user to confirm that correction is valid
Approaches for Handling Exceptional Conditions • Each method handles the exceptional conditions that arise during its execution • A low level class/method handles all exceptional conditions that may arise • All methods return status information so that client methods can respond to exceptional conditions ALL OF THESE APPROACHES HAVE PROBLEMS
I. Each method handles its own exceptional conditions info1 (in case an exception arises) Code to detect and handle exception info1, info2 (in case an exception arises) Code to detect and handle exception (use info1) Code to detect and handle exception (use info1, info2)
I. Each method handles its own exceptional conditions • No modularity or consistency • changes to error handling affect all the methods • May need to pass considerable information many levels to maintain context information • hard to provide user friendly response w/o knowing clients context • Must return status information so calling method can determine if it should proceed or terminate
II. A low level class/method handles exceptional conditions Exception handling class
II. A low level class/method handles exceptional conditions • Error processing handled in a more consistent and modular fashion • changes to error handling only affect the error handling class/method • May need to pass considerable information many levels to maintain context information • hard to provide user friendly response w/o knowing clients context • Must return status information so calling method can determine if it should proceed or terminate
III. Methods return status information so that client methods can respond to exceptional conditions • Calling method must always check status information • Calling methods must be able to respond to status information call Foo(bar, status1, status2, …, statusN); if status1 then do repair1; else if status2 then do repair2; else if . . . else normal processing using bar endif
Exceptions were added to languages to help with error processing • A method that detects a problem can handle the exception locally and then raise/throw/signal an exception to the methods in its calling context handler for E1 throw E1
A method can catch an exception and specialize its response handler for E2 handler for E1; throw E2 throw E1
Exception Handling Mechanisms • Signal/raise/throw an exception • predefined • user defined • Exception handlers • local • non-local • propagate through call stack • one level only • multiple levels
Exception Handling Mechanisms (cont.) • Execution after handler • resumption model: return to signal location • termination model: terminate execution of method • Java supports predefined and user defined exceptions, local and multi-level propagation, with termination
Exceptions in Java • Indicates an unusual situation (error) • Thrown at the point in the code where the error occurs • Caught by an exception handler • Can be handled locally • Can look back through call stack for the first handler • Methods must declare the exceptions they throw
Handling Exceptions try { i = s.pop( ); } catch( EmptyStackException i); { system.out.println( “Oops! The stack is empty!” ); i = 0; }
Handling multiple exceptions try { readFromFile( “foo” ); } catch( FileNotFoundException e); { system.out.println( “Oops! The file is missing!” ); } catch( IOException e ) { system.out.println( “Oops! Can’t read the file!” ); } finally { readFromFile( “foo.bak”); }
Try/Catch Statement • Exceptions raised in the try body are handled in the catch statements • Catch statements are evaluated in order • first match leads to execution of the catch body • Usually list exceptions from most specific to least specific • If there is a finally clause then it is always executed • May not execute all statements in try body • could be interrupted by an exception
Finding Exception Handlers • Look in enclosing blocks • Look in calling methods • If no exception handler is found in call stack, program crashes handler for E1 propagate E1 throw E1
Multiple Levels of Propagation getContent( _) { try { openConection( ); readData ( ); } catch (IOException e) { //handle IO error } } openConnection ( ) throws IOException { openSocket( ); sendRequest( ); …. } sendRequest ( ) throws IOException { write (body); //write error }
Explanation • Write throws the exception • sendRequest doesn’t handle the exception but must indicate that it propagates the exception • Same for openConnection • getContent catch statement handles the exception • May never execute the readData( ) statement in getContent
Throwing Exceptions int Dequeue (Queue q) throws QueueEmpty { if ( q.head == q.tail ) { throw new QueueEmpty ( ); } else { q.head = q.head + 1; return q.contents [q.head - 1]; } } class QueueEmpty extends Exception { }
Types of Java Exceptions • General exceptions • Must be explicitly thrown • Should be handled by all programs • Runtime exceptions • Frequent runtime problems • No need to explicitly state that such an exception might be thrown • Runtime message generated if they are not caught
Summary of Exception Handling • Exceptions allow the programmer to separate the handling of unusual cases from expected ones • Program should catch predefined exceptions and throw more specific exceptions when possible • Exception handling is difficult, even with exception handlers • Exception handling is an important part of most programs
Concurrent System • Multiple threads of execution • Logically concurrent: share a single processor • Physically concurrent: multiple processors • Run independently, for the most part • Typically, need to communicate • Share data • Pass messages • Typically, need to synchronize their activities
Threads in Java • A thread is a sequential flow of control within a program • has a beginning, an execution sequence, and an end • cannot be run on its own, but exists only within a larger program A program with three threads