8d42269d5f43e861e37353540c1a1069.ppt
- Количество слайдов: 34
Java Overview http: //www-sldnt. slac. stanford. edu/tony/talk/java-98/ Tony Johnson SLD 9 th January 1998
What will this talk cover? l Will discuss l – History of Language – What is Java – There a number of example programs, but intent is to give a feel for the language rather than go into too many details. – If there is sufficient interest it may be possible to arrange tutorial-like session(s) at a future date. • Language • Libraries – What is it good for – Why you should (perhaps) use it – How does it compare with other languages, particularly C, C++ – Future of Language • Lawsuits etc. – Conclusion Not a tutorial on how to program in Java l Appendix (left over slides) – Gives a brief introduction to language syntax and features.
What is Java? l History l – Originally designed (1991) as a small language for consumer electronics (cable boxes, toasters etc. ) – Eventually someone wrote Hot. Java Browser, which could run Java Applets – At height of internet craze, adopted by Netscape, Microsoft, Sun etc. as Web Programming Language. l More than just a Web Tool – Java is a fully functional, platform independent, programming language – Powerful set of machine independent libraries, including windowing (GUI) libraries. Past Year – Sun has released several new versions of language + libraries – >1, 000 copies of Java Development kit downloaded – Java available for MAC, Win 95/NT, HP, SUN, SGI, Digital Unix, Linux, Amiga, OS/2, BEOS, VMS, and even AIX – Microsoft <---Sues---> Sun l Next Year – Should see many real Java applications emerge
How does Java work? l l Java source code is compiled into machine independent “bytecodes” The bytecodes can be run directly by an interpreter The bytecodes can be converted to machine code and executed (“Just in Time (JIT)” compilation). An optimizing interpreter can dynamically identify program “hotspots” and create code optimized for the specific machine/environment. – Optimizing interpreter coming soon from SUN. Java Source code Compiler Java “Bytecodes” Mac Bytecode Unix PC JIT Compiler Interpreter Machine Code
Java Buzzwords l Simple l – well, simpler than C++ l Object Orientated – Runs on PC, MAC, Unix, VMS l – more so than C++ l l Secure – Bytecode “verifier”, padded cell High Performance – With JIT compiler still several times slower than native C++ – Coming soon! Optimizing interpreter from Sun, faster (? !? ) than C++ Robust – Difficult to create memory leaks, go beyond the end of an array, corrupt stack or code Interpreted – “Compiler” converts code into machine independent “bytecodes” Distributed – Built in support for Internet protocols, URL’s, HTTP etc. – Support for distributed objects, RMI, CORBA etc. Architecture Neural, Portable l Multithreaded – Language has direct support for multithreading (c. f. subprocesses) l Dynamic – Libraries can change without recompiling programs that use them
Java Language Features l Pure Object Oriented Language l – Can only write classes l Syntax very similar to C/C++, but without many of the rarely used, overly complex features of C++ – – No history No operator overloading No multiple inheritance No Pointers Supports – – l Inheritance Interfaces Nested Classes Automatic Garbage Collection Built in support for – – – Threads Exception handling Object serialization Networking Reflection
Java Libraries (API’s) l The usefulness of Java is greatly enhanced by the large range of platform independent libraries available: – – – AWT - Basic GUI toolkit - delegates to OS specific “Peers” SWING (a. k. a. JFC) Enhanced “Peerless” GUI toolkit (Beta) 2 D - Transformations, stroked fonts, pattern fill, textures etc. (Beta) JDBC - Standard Interface between Java and SQL databases ODMG binding - Standard Interface to Object databases RMI + CORBA - Remote procedure calls between distributed Java applications, and between Java and other languages – BEANS - Java based components, plug commercial components into your applications. – Media (audio, video etc. ), Share (e. g. whiteboards), Animation, Telephony, 3 D (developed by SUN and SGI), cryptography, server. (Beta)
What is Java Good For? l l Web Applets Database programming – SQL databases using JDBC – Object databases using ODMG binding l l Java Servlets Stand Alone Applications – GUI based applications l Distributed client-server applications – Using TCPIP + RMI + CORBA l Graphics applications – 2 D and 3 D l Physics Analysis
Hello World in Java
Java Applets l l Java Applets are programs designed to run inside a web browser. Instead of having a “main” method they have a class derived from “Applet” whose “init” method is called when the applet is loaded. The applet class provides capabilities for loading images, sounds and animations from the internet. Applets loaded from the internet are run inside a “sandbox” which restricts what they can do: – No Access to local filesystem – Can only open network connections with the site they came from l Problems – Lack of network/filesystem access can be restrictive – Complex programs can be large and hence slow to download – Sun has been introducing new releases far to fast for browser manufacturers to keep up. – Each browser has subtle differences. l Solutions? – Java activator from SUN • Plug in for netscape/IE to ensure latest SUN features always available. – Signed applets can be granted more privileges. • Can download local copies of large programs
Java Applet Example
Java SQL Database Access l Java provides standard interface to SQL databases, JDBC – Most database vendors now have implementations of JDBC for use with their database – Oracle has pure Java JDBC driver (no need to install SQLNet, SQLPlus etc. to be able to use it). l l Makes it possible to write database programs which are independent of the underlying database. Automatic translation of database types to native Java types: – e. g. Date/time in database is extracted as Java Date object, manipulation of dates straightforward.
Java SQL Database Access
Java Object Database Access l Using JDBC to connect to databases is fine for accessing legacy data in SQL databases. – Using SQL and pulling columns out of tables is a little inconvenient. – Would be better to create a network of related objects in Java and • “stick them all in a database” • “retrieve all or part of the network later” – This is what object databases are for • ODMG (Object Database Management Group) has defined a standard binding between Java and OO databases. • Several OO databases new support the ODMG Java binding
Java Object Database Access
Java Servlets l A Java Servlet runs on a web server instead of a web browser – Performs similar function to CGI scripts under Unix – Works with many web servers • Netscape, Microsoft IIS, Apache, Java Web Server, many more. . . – Machine independent – Much faster than CGI (no process forking) – Gives full power of Java for database access, data manipulation etc.
Real Applications in Java? l l So far all examples have been fairly trivial. Is it possible to write real applications in Java? Yes! (at least I hope so)
Java for Physics Analysis? l Java has good mix of power, simplicity, math, speed for physics analysis – SLD has developed a set of hep. analysis classes for Histograming – Networking support and mobility of code excellent for client server applications. • Analysis routine goes to data instead of data coming to analysis routine.
How to get started with Java l Download free Java Developer Kit (JDK) from SUN (www. javasoft. com) – – l Available for Windows, Solaris. Contains line mode compiler+debugger+misc. tools Similar kits available for many other platforms (from vendors) Solaris/AIX JDK installed for Unix at SLAC in /afs/slac/packages/java For more serious work get hold of a Java Integrated Development Environment – – Symantec Café (the oldest and most popular IDE at present) Visual J++ from Microsoft (beware of assimilation) Visual Age for Java from IBM Java Workshop from SUN • All contain integrated editor/debugger/source control • None have really good WYSIWYG layout tools (yet).
More Information l Books – Keep away from books whose focus is too web related – O’Reilly – Java in a Nutshell – Exploring Java – Core Java (Sun. Soft) • A little two thick for comfort, but comprehensive and down-to-earth – Learn Java Now (Microsoft) • Comes free with Visual J++ l Web Sites – http: //www. javasoft. com • Sun’s home page for Java – http: //www. javasoft. com/books/Series/Tutorial/index. html • Complete JAVA tutorial, in case you are too poor to buy the book – http: //www. gamelan. com/ • Huge library of Java applets and applications – http: //www. javaworld. com – http: //www. javareport. com • Java. World/Java Report (magazines) – http: //café. symantec. com/ • Café Web Site – http: //www. microsoft. com/visualj • Visual J++ – http: //www-sldnt. slac. stanford. edu/jas • Java Analysis Studio
Conclusion l If you are still using: – Fortran, C, C++, Perl, CGI, SQLPlus, Rexx, IDA etc. l you could save yourself a lot of time and effort by switching to:
Appendix Java Language Elements
Topics to be Covered l Java Language Features – – – – – l Variables, Operators, Expressions Statements Classes + Objects Inheritance Packages Exceptions Multithreading Data Structures Standard Libraries Plenty of example programs – Tutorial rather than real-world programs
Types, Variables, Operators, Expressions l Primitive Types l int, short, long, byte • all signed • size is machine independent float, double char • Stores single UNICODE character boolean l + - * / % ^ ++ -! ~ & | && || ? : << >> >>> < <= > >= == != l Strings – Java has nice UNICODE string type that supports concatenation, substrings, comparison etc. Variables and Expressions int a, b; double salary = 100000; float slac. Raise = 1. 00002; salary = salary * slac. Raise; salary *= slac. Raise; salary -= parking. Fine; Operators String s = “Your raise is ” + slac. Raise; l Notes: – if (a = 3) { } is illegal! – No operator overloading – No pointers! (But surprisingly you won’t miss them)
Statements l Again, very C like if (condition 1) {block 1} else if (condition 2) {block 2} else {block 3} for (int i=0 ; i<10 ; i++) {block} while (condition) {block} do {block} while (condition); l Unfortunately even the switch statement is just like C switch (choice) { case 1: case 2: … break; case 3: … break; default: … break; }
Introduction to OO Programming l Java is an object oriented programming language, so some rudimentary knowledge of OO terminology is required – Classes (e. g. “Employee”, “Track”) • Objects – specific instances of a class (e. g. “Tony Johnson”, “Track 5”) • In Java all functions are contained within classes • For largely historical reasons functions are often called methods or member functions – Inheritance (aka subclassing) • e. g. “Associate Director”, “Drift Chamber Track” – Encapsulation • Variables/Functions can be declared: – private • only functions within same class or superclass can access them (c. f. C++ protected) – public • any function can access them • Java also implements – static • Applies to class not object – final • Cannot be overridden by subclass
Classes class Employee Class Declaration { public Employee (String n, double s) Constructor { name = n; salary = s; } public Employee (String n) Overloaded Constructor { name = n; salary = 0; } public void raise. Salary(double by. Percent) { salary *= 1 + by. Percent / 100; } public double get. Salary() Access Method { return salary; } private String name; Private Member Variables private double salary; }
Objects l Objects represent instances of classes Employee java. Expert = new Employee(“Joe”, 100000); java. Expert. Raise. Salary(10); // Raise salary by 10% system. out. println(“Salary is” + java. Expert. Get. Salary()); l l Note that Java uses the keyword new for creation of new objects. Unlike C++ there is no delete keyword for the deletion of objects. – Java handles deletion of objects (and recovery of the memory they occupy) automatically as soon as there are no longer any references to them. – This makes writing code much easier, it is “impossible” to create a memory leak in Java. . – The process of keeping track of when objects are unreferenced and deleting them is called “garbage collection”. It does impose some processing overhead which slows down Java programs compared to equivalent programs in C or C++. èAppl_1 Example + Employee. Test Example
Inheritance class Manager Extends Employee Class Declaration { public Manager (String n, double s, Employee e) Constructor { name = n; salary = s; secretary = e; } public String Get. Secretary() New Access Method { return secretary; } public void Raise. Salary(double by. Percent) Overridden Method { double bonus = 10; super. Raise. Salary(by. Percent + bonus); } private Employee secretary; New member variables } èManager. Test Example
Interfaces l l Interfaces in Java are a replacement l Interfaces for the concept of “multiple – Objects can implement any number of interfaces inheritance” in C++. – Can have hierarchies of interfaces Suppose we want to sort managers by – Interfaces cannot have methods the number of employees they have. – Cleaner but not quite as powerful as multiple inheritance – Only way to implement “callbacks” in Java Employee Manager Sortable In C++ both Employee and Sortable can be classes l In Java one (probably sortable) must be an “interface” èEmployee Sort Example l l Enumeration Interface – Can loop over all elements of any class that implements the enumeration interface Enumeration e = thing. elements(); while (e. has. More. Elements()) { Thing t = e. get. Next. Element(); }
Arrays, Collections etc. l C++ l – “If you build it they will come” – Standard Template Library l Java has powerful built in objects – String – Arrays • Arbitrary size but cannot be resized – Vectors • Full dynamic sizing Built in objects continued… – Property Sets • Useful for storing program parameters – – – Bit Sets • Arbitrary size array of bits – Hash. Tables + Hash. Sets • Quick way to look up object in large collection Linked Lists Queues Stacks Multi-Dimensional Arrays Full featured “Collections” coming in JDK 1. 2 èSieve Example (Benchmark) – – C++ 1. 53 seconds Java 59. 93 seconds Visual Basic 65. 69 seconds Microsoft JIT compiler ? 3 seconds
Threads l Threads are similar to “fork” or “spawn” but – Threads run in same address space, not separate process • Very efficient • Very dangerous – All modern operating systems have support for threads l Java has built-in support for threads – Just derive a class from thread – Issue the start() method on the object èBouncing Ball Example l Java Threads support – – Priorities Interrupts Thread groups Synchronization • synchronized keyword can be applied to classes or methods – Timers
Java AWT Package l AWT allows development of platform independent GUI programs – Java takes a “Lowest Common Denominator” approach • Supports only one mouse button • Doesn’t “look as nice” as native windows/MAC applications • Available graphical layout tools are quite limited. – Moderate set of graphic objects • Buttons, Labels, Text Input, Menus, • Scroll Bars, Dialogs, Radio Buttons – Mapped onto native GUI objects on each platform. l “Layouts” are used to compensate for the fact that GUI objects may have different sizes on different platforms – Limited set of layouts are provided • • Flow Layout Border Layout Card Layout Grid (Bag) Layout – User defined layouts needed for most real programs èHello. World Example
Java for Physics? Java Compiler Experiment Extensions (Event Display) import physics. hep. *; GUI Network Data Analysis Engine Users Java Code Experiment Interface class My. Analysis extends Analysis { public void init() { h = new Hist(“Energy”); } public void Evanal(Event e) { Enumeration x = e. get. Tracks(); while (x. has. More. Elements()) { Track t = x. get. Next. Element(); h. Add(t. get. Energy()); } } private Histogram h; }