92
Institute for Visualization and Perception Research IV P R 1 © Copyright 1998 Haim Levkowitz The Java Programming Language A Quick Tour of Java …

The Java Programming Language

Embed Size (px)

DESCRIPTION

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 ... - PowerPoint PPT Presentation

Citation preview

Page 1: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 1

© Copyright 1998 Haim Levkowitz

The Java Programming Language

• A Quick Tour of Java …

Page 2: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 2

© Copyright 1998 Haim Levkowitz

Getting Started ...

• Why Java?

• What Is Java? ...

• Two Simple Examples ...

• Executing a Java Applet ...

• Java Virtual Machine ...

• Java and the Web ...

• Java vs. C ...

Page 3: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 3

© Copyright 1998 Haim Levkowitz

Properties of Java (claimed & desired) ...

• Simple ...• Object-oriented ...• Distributed ...• Interpreted ...• Robust ...• Secure ...• Architecture neutral ...• Portable ...• High-performance ...• Multithreaded ...• Dynamic ...

Page 4: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 4

© Copyright 1998 Haim Levkowitz

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

Page 5: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 5

© Copyright 1998 Haim Levkowitz

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

Page 6: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 6

© Copyright 1998 Haim Levkowitz

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

Page 7: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 7

© 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

Page 8: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 8

© Copyright 1998 Haim Levkowitz

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

Page 9: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 9

© Copyright 1998 Haim Levkowitz

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

Page 10: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 10

© Copyright 1998 Haim Levkowitz

Application Safety 4 Layers ...

• Layer 1: Language and Compiler ...

• Layer 2: Bytecode Verifier ...

• Layer 3: Classloader ...

• Layer 4: Interface-specific Security ...

Page 11: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 11

© Copyright 1998 Haim Levkowitz

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

Page 12: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 12

© Copyright 1998 Haim Levkowitz

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

Page 13: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 13

© Copyright 1998 Haim Levkowitz

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

Page 14: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 14

© Copyright 1998 Haim Levkowitz

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

Page 15: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 15

© Copyright 1998 Haim Levkowitz

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

Page 16: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 16

© 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

Page 17: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 17

© Copyright 1998 Haim Levkowitz

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.

Page 18: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 18

© Copyright 1998 Haim Levkowitz

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

Page 19: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 19

© Copyright 1998 Haim Levkowitz

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

Page 20: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 20

© 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

Page 21: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 21

© Copyright 1998 Haim Levkowitz

Two Simple Examples ...

• Hello, world ...

• A scribble applet ...

Page 22: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 22

© Copyright 1998 Haim Levkowitz

Hello, world ...

class HelloWorld {public static void main(String[] args) {

System.out.println("Hello, world");}

}javac HelloWorld.java ==>

HelloWorld.classjava HelloWorld

Page 23: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 23

© Copyright 1998 Haim Levkowitz

A scribble applet ...

• 1-2-Scribble.java

Page 24: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 24

© Copyright 1998 Haim Levkowitz

Executing a Java Applet ...• Compile ==>

stand-alone code

• Distributed applets

Java source

Java compiler

Java bytecode

Bytecode loader

Bytecode verifier

Bytecode interpreterJust-in-time

compilerJava run-time

Hardware

Network or file system

or

Page 25: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 25

© Copyright 1998 Haim Levkowitz

Java Virtual Machine ...• SW simulation of idealistic HW architecture

• Execute Java bytecodes• Java instruction ...• Virtual machine architecture

specification ...• Current implementation (Sun) ...• Bytecode execution ...

Page 26: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 26

© Copyright 1998 Haim Levkowitz

Java instruction ...

• One-byte opcode: operation• 0 or more operands• Inner loop of the JVM

do {fetch an opcode byteexecute an action depending on

value of opcode} while (there is more to do);

Page 27: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 27

© Copyright 1998 Haim Levkowitz

Virtual machine architecture specification ...• Basic set of supported data types

• No specific internal structure of objects

Page 28: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 28

© Copyright 1998 Haim Levkowitz

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

Page 29: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 29

© Copyright 1998 Haim Levkowitz

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 ...

Page 30: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 30

© Copyright 1998 Haim Levkowitz

VM executes single method at a time ...

• Multithreading through built-in threads lib

• SW construct

• Doesn't depend on specific HW support

Page 31: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 31

© Copyright 1998 Haim Levkowitz

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

Page 32: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 32

© Copyright 1998 Haim Levkowitz

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

Page 33: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 33

© Copyright 1998 Haim Levkowitz

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

Page 34: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 34

© Copyright 1998 Haim Levkowitz

Java and the Web …

• Simple Applet

• Embedding in Web page ...

Page 35: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 35

© Copyright 1998 Haim Levkowitz

Simple Applet

import java.awt.*;import java.applet.*;public class Wave extends Applet {

int n = 1public 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. ...

Page 36: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 36

© Copyright 1998 Haim Levkowitz

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; }

}

Page 37: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 37

© Copyright 1998 Haim Levkowitz

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>

Page 38: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 38

© Copyright 1998 Haim Levkowitz

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 ...

Page 39: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 39

© Copyright 1998 Haim Levkowitz

Program Structure and Environment ...

• Command-line arguments ...

• Program exit value ...

• Environment ...

Page 40: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 40

© Copyright 1998 Haim Levkowitz

Command-line arguments ...

• Single argument to main(): array of strings, argv[]

• argv.length

Page 41: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 41

© Copyright 1998 Haim Levkowitz

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

Page 42: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 42

© Copyright 1998 Haim Levkowitz

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)

Page 43: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 43

© Copyright 1998 Haim Levkowitz

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 ...

Page 44: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 44

© Copyright 1998 Haim Levkowitz

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

Page 45: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 45

© Copyright 1998 Haim Levkowitz

Packages, classes, and directory structure ...

• Compiled class in separate file ...

• Source code: .java ...

Page 46: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 46

© Copyright 1998 Haim Levkowitz

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

Page 47: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 47

© Copyright 1998 Haim Levkowitz

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

Page 48: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 48

© Copyright 1998 Haim Levkowitz

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

Page 49: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 49

© Copyright 1998 Haim Levkowitz

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

Page 50: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 50

© Copyright 1998 Haim Levkowitz

Globally unique package names ...

• Internet-wide unique package naming scheme• Based on domain names

java.lang.Sring.substring()

package name class method

package name class

domain prefix

Page 51: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 51

© Copyright 1998 Haim Levkowitz

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

Page 52: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 52

© 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 ...

Page 53: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 53

© Copyright 1998 Haim Levkowitz

Three forms ...

• import package; ...

• import package.class; ...

• import package.*; ...

Page 54: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 54

© Copyright 1998 Haim Levkowitz

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

Page 55: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 55

© Copyright 1998 Haim Levkowitz

importpackage.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

Page 56: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 56

© Copyright 1998 Haim Levkowitz

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

Page 57: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 57

© Copyright 1998 Haim Levkowitz

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 ...

Page 58: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 58

© Copyright 1998 Haim Levkowitz

All accessible to all others in same package ...

• Can't define classes visible only in single file

Page 59: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 59

© Copyright 1998 Haim Levkowitz

Public class in pkg accessible within another pkg ...

• Non-public class not accessible outside package

Page 60: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 60

© Copyright 1998 Haim Levkowitz

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

Page 61: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 61

© Copyright 1998 Haim Levkowitz

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

Page 62: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 62

© Copyright 1998 Haim Levkowitz

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

Page 63: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 63

© Copyright 1998 Haim Levkowitz

No Preprocessor ...

• Defining constants ...

• Defining macros ...

• Including files ...

• Conditional compilation ...

Page 64: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 64

© Copyright 1998 Haim Levkowitz

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

Page 65: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 65

© Copyright 1998 Haim Levkowitz

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

Page 66: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 66

© Copyright 1998 Haim Levkowitz

E.g., java.lang.Math.PI ...

public final class Math {

...

public static final double PI = 3.14159.....;

...

}

Page 67: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 67

© Copyright 1998 Haim Levkowitz

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

Page 68: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 68

© Copyright 1998 Haim Levkowitz

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)

Page 69: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 69

© Copyright 1998 Haim Levkowitz

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

Page 70: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 70

© Copyright 1998 Haim Levkowitz

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

Page 71: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 71

© 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 ...

Page 72: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 72

© Copyright 1998 Haim Levkowitz

The boolean type ...

• Contains: true or false

• Default: false

• Size: 1 bit

• Min value: NA

• Max value: NA

Page 73: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 73

© Copyright 1998 Haim Levkowitz

The char type ...

• Contains: Unicode character

• Default: \u0000

• Size: 16 bits

• Min value: \u0000

• Max value: \uFFFF

Page 74: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 74

© Copyright 1998 Haim Levkowitz

Integral types ...

• All are signed (except char)• Division by 0 ==> ArithmeticException

thrown• byte ...• short (NOT short int!) ...• int ...• long (NOT long int!) ...

Page 75: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 75

© Copyright 1998 Haim Levkowitz

byte ...

• Contains: signed integer

• Default: 0

• Size: 8 bits

• Min value: -128

• Max value: 127

Page 76: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 76

© Copyright 1998 Haim Levkowitz

short (NOT short int!) ...

• Contains: signed integer

• Default: 0

• Size: 16 bits

• Min value: -32768

• Max value: 32767

Page 77: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 77

© Copyright 1998 Haim Levkowitz

int ...

• Contains: signed integer

• Default: 0

• Size: 32 bits

• Min value: -2147483648

• Max value: 2147483647

Page 78: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 78

© Copyright 1998 Haim Levkowitz

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

Page 79: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 79

© Copyright 1998 Haim Levkowitz

Floating-point types ...

• float ...

• double ...

• Special values ...

Page 80: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 80

© Copyright 1998 Haim Levkowitz

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

Page 81: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 81

© Copyright 1998 Haim Levkowitz

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

Page 82: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 82

© Copyright 1998 Haim Levkowitz

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 ...

Page 83: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 83

© Copyright 1998 Haim Levkowitz

Negative zero compares equal to positive zero ...

• 1/-0 = NEGATIVE_INFINITY

• 1/0 = POSITIVE_INFINITY

• Floating point arithmetic never causes exception

Page 84: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 84

© Copyright 1998 Haim Levkowitz

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 ...

Page 85: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 85

© Copyright 1998 Haim Levkowitz

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"

Page 86: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 86

© Copyright 1998 Haim Levkowitz

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

Page 87: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 87

© Copyright 1998 Haim Levkowitz

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 ...

Page 88: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 88

© 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

Page 89: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 89

© Copyright 1998 Haim Levkowitz

To copy array values ...

• Assign each value individually, or

• Use System.arraycopy() method

Page 90: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 90

© Copyright 1998 Haim Levkowitz

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

Page 91: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 91

© Copyright 1998 Haim Levkowitz

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

Page 92: The Java Programming Language

Institute for Visualization and Perception ResearchI VPR 92

© Copyright 1998 Haim Levkowitz

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