Transcript 09_java

The Java Programming
Language
• A Quick Tour of Java …
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
1
Getting Started ...
•
•
•
•
•
•
•
Why Java?
What Is Java? ...
Two Simple Examples ...
Executing a Java Applet ...
Java Virtual Machine ...
Java and the Web ...
Java vs. C ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
2
Properties of
Java (claimed
& desired) ...
I VPR
•
•
•
•
•
•
•
•
•
•
•
Simple ...
Object-oriented ...
Distributed ...
Interpreted ...
Robust ...
Secure ...
Architecture neutral ...
Portable ...
High-performance ...
Multithreaded ...
Dynamic ...
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
3
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
4
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
5
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
for Visualization
and Perception Research
I V P R Institute
• ==>
Distributed
clients & servers 6
© Copyright 1998 Haim Levkowitz
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
7
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
8
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
9
Application Safety 4
Layers ...
•
•
•
•
Layer 1: Language and Compiler ...
Layer 2: Bytecode Verifier ...
Layer 3: Classloader ...
Layer 4: Interface-specific Security ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
10
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
11
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
12
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
13
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
14
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
15
Institute for Visualization and Perception Research
I VPR
© Copyright 1998 Haim Levkowitz
Architecture neutral ...
• Originally: Consumer electronics
• Next: network-based applications
• Also: cross platform
• With java.awt: appropriate behavior
and appearance for each
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
16
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.
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
17
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
18
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
19
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
20
Two Simple Examples ...
• Hello, world ...
• A scribble applet ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
21
Hello, world ...
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world");
}
}
javac HelloWorld.java ==>
HelloWorld.class
java HelloWorld
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
22
A scribble applet ...
• 1-2-Scribble.java
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
23
Executing
a Java
Applet ...
• Compile ==>
stand-alone
code
• Distributed
applets
I VPR
Java
source
Java
compiler
Java
bytecode
Network
or file
system
Bytecode
loader
Bytecode
verifier
or
Bytecode
interpreter Just-in-time
compiler
Java
run-time
Hardware
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
24
Java Virtual Machine ...
• SW simulation of idealistic HW
architecture
• Execute Java bytecodes
• Java instruction ...
• Virtual machine architecture
specification ...
• Current implementation (Sun) ...
• Bytecode execution ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
25
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);
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
26
Virtual machine
architecture specification
...
• Basic set of supported data types
• No specific internal structure of
objects
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
27
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
28
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 ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
29
VM executes single
method at a time ...
• Multithreading through built-in threads
lib
• SW construct
• Doesn't depend on specific HW
support
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
30
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
31
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
32
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
33
Java and the Web …
• Simple Applet
• Embedding in Web page ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
34
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. ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
35
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; }
}
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
36
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>
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
37
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 ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
38
Program Structure and
Environment ...
• Command-line arguments ...
• Program exit value ...
• Environment ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
39
Command-line arguments
...
• Single argument to main(): array of
strings, argv[]
• argv.length
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
40
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
41
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)
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
42
•
•
•
•
•
•
•
•
The Name Space:
Packages, Classes, & Fields
...global variables ...
No
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 ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
43
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_na
me (field: var / method
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
44
Packages, classes, and
directory structure ...
• Compiled class in separate file ...
• Source code: .java ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
45
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
46
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
47
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
48
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
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
49
Globally unique package
names ...
• Internet-wide unique package naming scheme
• Based on domain names
package name
class
method
java.lang.Sring.substring()
package name
class
domain prefix
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
50
The package statement ...
• First text other than comments, whitespace
• Which package this code is part of
• ==> Access to all classes in package
• ==> Access to all non-private methods & fields in
classes
• Compiled class must be placed in appropriate
position in CLASSPATH dir. hierarchy
• If omitted ==> code is part on unnamed default
package
• ==> Can be interpreted from current dir
• ==> Convenient for small test programs
51
I V P R Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
The import statement ...
• Make classes available to current class
under abbreviated name
• Public classes always available by
fully qualified name
• Any number, but must appear
• After package statement
• Before first class / interface def
• Three forms ...
52
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
Three forms ...
• import
• import
• import
I VPR
package; ...
package.class; ...
package.*; ...
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
53
import
package; ...
• Spec'd package by name of its last
component
• E.g., import java.awt.image;
• ==> Can call
java.awt.image.ImageFilter just
ImageFilter
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
54
import
package.class; ...
• Spec'd class in package by its class
name alone
• E.g., import java.util.Hashtable
• ==> Can use Hashtable instead of
java.util.Hashtable
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
55
import
package.*; ...
• All classes in package available by
their class name
• E.g., import java.lang.*;
• Implicit (no need to specify)
• ==> Make core classes available by
unqualified class names
• Ambiguous class names ==> must use
full name
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
56
Access to packages,
classes, and fields ...
•
•
•
•
Package accessible if files/dir's are accessible
All accessible to all others in same package ...
Public class in pkg accessible within another pkg ...
All fields (var's, methods) of a class are accessible
within class
• Fields in class accessible from diff class in same
pkg ...
• Fields in class accessible from diff package if ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
57
All accessible to all others
in same package ...
• Can't define classes visible only in
single file
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
58
Public class in pkg accessible
within another pkg ...
• Non-public class not accessible
outside package
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
59
Fields in class accessible
from diff class in same
pkg ...
• ... if not
• private, or
• accessible only within own class
• private protected
• accessible only within own class
and within subclass
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
60
Fields in class accessible
from diff package if ...
• Class is accessible
• Field declared public, or
• Field declared protected or private
protected and access is from subclass
of class
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
61
Comments ...
• 1. /* Standard C-style */
• Cannot be nested
• 2. // C++-style
• Use if want to comment out blocks
• No preprocessor #if 0 to comment out
block
• 3. /** Special "doc comment" */
• Processed by javadoc ==> simple online
doc
• Cannot be nested
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
62
No Preprocessor ...
•
•
•
•
Defining constants ...
Defining macros ...
Including files ...
Conditional compilation ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
63
Defining constants ...
•
•
•
•
•
•
•
Declare variable final ...
E.g., java.lang.Math.PI ...
Note
C convention of CAPITAL
Globally unique hierarchical names
==> No name collision
Strongly typed ==> better type-checking by
compiler
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
64
Declare variable final ...
• Must specify initializer when declared
• Equivalent of C #defined: static final
• Within class definition
• If compiler can compute value, uses
value to pre-compute other
constants referring value
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
65
E.g., java.lang.Math.PI ...
public final class Math {
...
public static final double PI =
3.14159.....;
...
}
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
66
Defining macros ...
• C preprocessor
• Looks like function invocation
• Replaced directly with C code
• Save overhead of function call
• No equivalent in Java
• Compiler might help
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
67
Including files ...
• No #include; no need
• Mapping of fully qualified class names to directory
& file structure
• E.g., java.lang.Math and java/lang/Math.class
• Compiler knows exactly where to find what needs
• No diff between declaring var / proc & defining
• ==> No need for header files, function prototypes
• ==> Single object file: def'n & implementation
• Import ==> shorter names (e.g., Math.PI)
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
68
Conditional compilation ...
• No #ifdef, #if
• Good compiler won't compile code known to
never be executed
• ==> if (false) block equiv. to #if 0 #endif in C
• Works with constants; E.g.,
• private static final boolean DEBUG = false;
• if (DEBUG) block not compiled
• Change DEBUG to true to activate
debugging
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
69
Unicode and Character
Escapes ...
• Characters, strings, identifiers in 16-bit Unicode
characters
• ==> Easier to internationalize
• Compatible w/ ASCII
• First 256 chars (0x0000 – 0x00FF) identical to
ISO8859-1 (Latin-1) 0x00 – 0xFF
• String API makes char rep'n transparent
• Unicode escape sequence: \uxxxx (if platform
can't display all 34,000 Unicode char's)
• Also full support of C char escape sequences
70
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
Primitive Data Types ...
• byte and boolean primitive type + standard set of C
types
• Strictly defined size and signdness of types
• All variables have guaranteed default values
• The boolean type ...
• The char type ...
• Integral types ...
• Floating-point types ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
71
The boolean type ...
•
•
•
•
•
Contains: true or false
Default: false
Size: 1 bit
Min value: NA
Max value: NA
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
72
The char type ...
•
•
•
•
•
Contains: Unicode character
Default: \u0000
Size: 16 bits
Min value: \u0000
Max value: \uFFFF
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
73
Integral types ...
• All are signed (except char)
• Division by 0 ==> ArithmeticException
thrown
• byte ...
• short (NOT short int!) ...
• int ...
• long (NOT long int!) ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
74
byte ...
•
•
•
•
•
Contains: signed integer
Default: 0
Size: 8 bits
Min value: -128
Max value: 127
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
75
short (NOT short int!) ...
•
•
•
•
•
Contains: signed integer
Default: 0
Size: 16 bits
Min value: -32768
Max value: 32767
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
76
int ...
•
•
•
•
•
Contains: signed integer
Default: 0
Size: 32 bits
Min value: -2147483648
Max value: 2147483647
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
77
long (NOT long int!) ...
•
•
•
•
•
•
Contains: signed integer
Default: 0
Size: 64 bits
Min value: -9.223372036854775808
Max value: 9.223372036854775807
Can append L or l to long constants
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
78
Floating-point types ...
• float ...
• double ...
• Special values ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
79
float ...
•
•
•
•
•
•
Contains: IEEE 754 floating-point
Default: 0.0
Size: 32 bits
Min value: ±3.40282347E+38
Max value: ±1.40239846E-45
Can append F or f to value
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
80
double ...
•
•
•
•
•
•
Contains: IEEE 754 floating-point
Default: 0.0
Size: 64 bits
Min value: ±1.79769313486231579E+308
Max value: ±4.94065645841246544E-324
Can append D or d to value
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
81
Special values ...
•
•
•
•
In java.lang.Float, java.lang.Double
POSITIVE_INFINITY
NEGATIVE_INFINITY
NaN
• Unorderd ==> comparison yields false
• Use Float.isNaN(), Double.isNaN() to test
• Negative zero compares equal to positive zero ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
82
Negative zero compares
equal to positive zero ...
• 1/-0 = NEGATIVE_INFINITY
• 1/0 = POSITIVE_INFINITY
• Floating point arithmetic never causes
exception
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
83
Reference (Non-primitive)
Data Types ...
•
•
•
•
•
•
•
•
•
Handled by reference (primitive types handled by value)
No &, *, -> operators
Two diff vars may refer to same object ...
Not true of primitive types ...
Copying objects
Checking objects for equality ...
Java has no pointers ...
null ...
Reference type summary ...
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
84
Two diff vars may refer to
same object ...
Button a, b;
p = newButton(); // p refs to Button object
q = p;
// q refs to same Button
p.setLabel("OK"); // Change object through p ...
String s = q.getLabel(); // ... also visible through q
// s now contains "OK"
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
85
Not true of primitive types
...
int i = 3; // i contains value 3
int j = i; // j contains copy of value in i
i = 2;
// changing i doesn't change j
// Now, i == 2; j == 3
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
86
Copying objects
•
•
•
•
•
•
•
Button a = newButton("OK");
Button b = newButton("Cancel");
a = b;
a contains ref to object that b ref's to
Object that a used to ref to is lost
To copy, use clone() method ...
To copy array values ...
87
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
To copy, use clone()
method ...
•
•
•
•
Vector b = newVector;
c = b.clone();
Not all types support clone()
Only classes that implement Cloneable
interface may be cloned
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
88
To copy array values ...
• Assign each value individually, or
• Use System.arraycopy() method
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
89
Checking objects for
equality ...
• == : 2 vars ref same object (not 2
objects have same value)
• To compare values, use method for
object type
• equals() in some classes
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
90
Java has no pointers ...
•
•
•
•
Auto ref, deref of objects
Can't cast object / array ref --> int (or vice versa)
No pointer arithmetic
Can't compute size in bytes of primitive type /
object
• ==> Avoid pointer bugs
• ==> Better security
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
91
null ...
• Reserved value: “absence of reference”
• Var doesn't refer to any object / array
• Default valued of all reference types
• Reserved keyword
• May be assigned to any variable of
reference type
• Cannot be cast to any primitive type
• Not equal zero
I VPR
Institute for Visualization and Perception Research
© Copyright 1998 Haim Levkowitz
92