970 likes | 1.51k Views
The Java Programming Language. A Quick Tour of Java …. Getting Started. Why Java? What Is Java? ... Two Simple Examples ... Executing a Java Applet ... Java Virtual Machine ... Java and the Web ... Java vs. C. Properties of Java (claimed & desired). Simple ... Object-oriented ...
E N D
The Java Programming Language • A Quick Tour of Java …
Getting Started ... • Why Java? • What Is Java? ... • Two Simple Examples ... • Executing a Java Applet ... • Java Virtual Machine ... • Java and the Web ... • Java vs. C ...
Properties of Java (claimed & desired) ... • Simple ... • Object-oriented ... • Distributed ... • Interpreted ... • Robust ... • Secure ... • Architecture neutral ... • Portable ... • High-performance ... • Multithreaded ... • Dynamic ...
Simple ... • Small number of language constructs • Look familiar: like C / C++ • No goto (break & continue instead) • No header files • No C preprocessor • No struct, union, operator overloading, multiple inheritance • No pointers: auto handling of de/referencing • Auto garbage collection
Object-oriented ... • Data • Methods • Class: data + methods • Describe state & behavior of object • Hierarchy: subclass inherit behavior from superclass • Packages of classes • java.awt (Abstract Windowing Toolkit): create GUI components • java.io: I/O • java.net: Network functionality • Object class in java.lang package • root of Java class hierarchy • most things are objects • numeric, character, boolean types only exceptions
Distributed ... • Network connectivity: classes in java.net • E.g., URL class: open & access remote objects on Internet • ==> Remote / local files same • Socket class: stream network connections • ==> Distributed clients & servers
Interpreted ... • Bytecodes (no machine code) • Java interpreter to execute compiled bytecodes • Architecture-neutral object file format • ==> Portable to multiple platforms • Java Virtual Machine • Java interpreter • Run-time system • Link: only to load new classes into environment • ==> Rapid prototyping / easy experimentation
Robust ... • Original design for consumer electronics • Strongly typed ==> compile-time check for type-mismatch • Requires explicit method declarations • Memory model • No pointers ==> no memory overwriting / corrupting • Automatic garbage collection • Run-time checks: e.g., array / string access within bounds • Exception handling: try/catch/finally statement • ==> group all error handling in one place • ==> Simpler error handling & recovery
Secure … • Application Safety 4 Layers ... • Solid examination of security • Bugs identified & corrected: http://java.sun.com/sfaq • The Princeton Hacks • Three problems • Rogue classloader • IP Spoofing • Denial-of-service
Application Safety 4 Layers ... • Layer 1: Language and Compiler ... • Layer 2: Bytecode Verifier ... • Layer 3: Classloader ... • Layer 4: Interface-specific Security ...
Layer 1: Language and Compiler ... • Memory allocation model • Compiler doesn't handle memory layout • ==> Can't guess actual memory layout • No pointers ==> all memory references via symbolic handles • Memory reference --> real memory at run-time by interpreter
Layer 2: Bytecode Verifier ... • Java code can be loaded over untrusted network • ==> Take into account potential hostile Java compilers • Runtime system: all code through theorem prover ... • Checks also verify stack overflows ==> interpreter exec faster
Runtime system: all code through theorem prover ... • Verify that code • Doesn't forge pointers to illegally manipulate objects outside VM • Doesn't violate access restrictions • Access objects according to correct type • Use correct type for all instruction parameters • Use legal object field accesses according to their private, public, or protected def'n
Layer 3: Classloader ... • Loaded classes in separate namespace than local • Prevent malicious applet from replacing standard applet • Single namespace for all classes from local file sys
Layer 4: Interface-specific Security ... • Interface to standard networking protocols • HTTP, FTP, etc. • Network package configured to provide diff levels of security • 1. Disallow all network accesses • 2. Allow network accesses to only hosts from which code was imported • 3. Allow network accesses only outside firewall if code came from outside • 4. Allow all network accesses
Architecture neutral ... • Originally: Consumer electronics • Next: network-based applications • Also: cross platform • With java.awt: appropriate behavior and appearance for each
Portable ... • Architecture neutral • No implementation-dependent aspects of language spec's • E.g., explicitly specify size of each primitive data type • And arithmetic behavior • Java compiler written in Java • Java run-time system written in ANSI C.
High-performance ... • Interpreted ==> avg. 20 time slower than C • Still adequate for interactive, GUI-, network-based app's • For critical performance: "just in time" compilers • Translate Java bytecodes --> machine code at run-time • Performance nearly as good as native C / C++ • Middle: between C / C++ and Tcl / UNIX shells • Better than Perl
Multithreaded ... • Need locks to prevent deadlocks • Built-in support: Thread class (in java.lang package) • Support methods to start / run / stop / check thread • Synchronization primitives • Prevents certain methods from running concurrently • ==> Ensure consistent state of variables
Dynamic ... • E.g., load classes across network as needed • Classes have run-time representation • Object can check which is its class • Can dynamically link classes into a running system
Two Simple Examples ... • Hello, world ... • A scribble applet ...
Hello, world ... class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world"); } } javac HelloWorld.java ==> HelloWorld.class java HelloWorld
A scribble applet ... • 1-2-Scribble.java
Executing a Java Applet ... • Compile ==> stand-alone code • Distributed applets
Java Virtual Machine ... • SW simulation of idealistic HW architecture • Execute Java bytecodes • Java instruction ... • Virtual machine architecture specification ... • Current implementation (Sun) ... • Bytecode execution ...
Java instruction ... • One-byte opcode: operation • 0 or more operands • Inner loop of the JVM do { fetch an opcode byte execute an action depending on value of opcode } while (there is more to do);
Virtual machine architecture specification ... • Basic set of supported data types • No specific internal structure of objects
Current implementation (Sun) ... • Object reference as handle w / pair of pointers • 1 --> object's method table • 2 --> data allocated by object • (another option: in-line caching rather than method table dispatch) • Written in C • Pointers don't violate security model / lack of pointers • Can't access VM pointers directly from Java source code / compiled Java bytecode
Bytecode execution ... • Like simple RISC microprocessor • Program counter: address of current bytecode • VM executes single method at a time ... • Add'l registers: info on current exec. method ... • Java VM instructions ...
VM executes single method at a time ... • Multithreading through built-in threads lib • SW construct • Doesn't depend on specific HW support
Add'l registers: info on current exec. method ... • vars: reference memory space allocated for method's local variable • optop: point to method's operand stack • frame: point to method's execution environment structure • Size of memory spaces pointed by registers well def'd at compile time
Java VM instructions ... • Take operands from operand stack • Operate on them • Return results to stack • Stack organization easy to emulate efficiently on machines w/ limited # of registers • E.g., Intel 486
Instruction categories ... • Stack manipulation (load, store, move) • Array management • Arithmetic (integer, floating point) • Logical • Control transfer • Method invocation and return • Exception handling • Monitors • Implement locking mechanisms • Provide exclusive access
Java and the Web … • Simple Applet • Embedding in Web page ...
Simple Applet import java.awt.*; import java.applet.*; public class Wave extends Applet { int n = 1 public void paint(Graphics g) { double y = 0.0, oy = 0.0; for (int x = 0; x < size().width; oy = y, y = 0, x++) { for (int j = 0; j < n; j++) y += Math.sin((2 * j + 1) * x / 15.0) / ( 2 * j + 1); Cont. ...
Cont. ... y = 0.47 * y + 0.5; if (x > 0) g.drawLine(x, (int)(oy * size().height), x + 1, (int)(y * size().height)); } } public boolean mouseDown (java.awt.Event evt. int x, int y) { n = n < 15 ? n + 1 : 1 ; repaint (); return true; } }
Embedding in Web page ... <html> This simple applet example draws a sine wave. <hr> <applet codebase="classes" code="Wave.class" width=600 height=100> </applet> </html>
Java vs. C ... • Program Structure and Environment ... • The Name Space: Packages, Classes, & Fields ... • Comments ... • No Preprocessor ... • Unicode and Character Escapes ... • Primitive Data Types ... • Reference (Non-primitive) Data Types ... • Objects ... • Arrays ... • Strings ... • Operators ... • Statements ... • Exceptions and Exception Handling ... • Miscellaneous Differences ...
Program Structure and Environment ... • Command-line arguments ... • Program exit value ... • Environment ...
Command-line arguments ... • Single argument to main(): array of strings, argv[] • argv.length
Program exit value ... • main() must be declared to return void • Can't return in main() • Use System.exit() to return value • Interpreter exits immediately • OS dependent
Environment ... • No reading OS env var's (OS dependent) • Instead, system properties (OS independent) • Lookup with System.getProperty() method • Set of standard sys prop's • Can insert add'l (-D option to interpreter)
The Name Space: Packages, Classes, & Fields ... • No global variables ... • Packages, classes, and directory structure ... • Packages of the Java API ... • The Java class path ... • Globally unique package names ... • The package statement ... • The import statement ... • Access to packages, classes, and fields ...
No global variables ... • Variables, methods within class • Class part of package • ==> Var's, methods ref'd by fully qualified name • Package_name.Class_name.Field_name (field: var / method
Packages, classes, and directory structure ... • Compiled class in separate file ... • Source code: .java ...
Compiled class in separate file ... • Same name as class, w/ .class extension • Stored in directory w / same components as package name • E.g., Pkg.Sub.Subsub.class_name in Pkg/sub/subsub/class_name.class
Source code: .java ... • One or more class def'ns • If more than one, only one declared public • I.e., available outside package • Must have same name as source file (wo .java) • Multiple classes in source compiled to multiple .class files
Packages of the Java API ... • java.applet: implementing applets • java.awt: graphics, text, windows, GUIs • java.awt.image: image processing • java.awt.peer: platform-independent GUI toolkit • java.io: input / output • java.lang: core language • java.net: networking • java.util: useful data types
The Java class path ... • Interpreter looks up class • System classes in • Platform-dependent default location, or • Relative to dir. spec'd by -classpath arg • User defined classes in • Current directory, and • Relative to dir's spec'd by CLASSPATH env. var. • E.g., on UNIX: setenv CLASSPATH .:~/classes:/usr/local/classes
Globally unique package names ... • Internet-wide unique package naming scheme • Based on domain names