93
A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

Embed Size (px)

Citation preview

Page 1: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

A Quick Intro to Java for C and C++ Programmers

Scott Hudson

HCI 631

Fall 2000

Page 2: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

2

About this lecture

Will be assuming you are a fluent C or C++ programmer.

This is going to be a quick introduction to the language.

I'm not going to teach anything much about object-oriented programming.

Page 3: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

3

What is Java

Java is a programming language designed by James Gosling at Sun – Designed to be "squirted" across a network into

a device, the primary device right now being a web browser

– Interpreted from byte codes (virtual machine approach)

– Dynamically loaded

=> very portable (except...)

Page 4: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

4

What is Java

"A pretty good object oriented language with C++ camouflage on"

Once was "The latest thing" and massively hyped

Page 5: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

5

Why was there hype about Java?

At the right place at the right time (important need on the web) – (Supposed to be) Highly portable (finally

is)– Seen by lots of companies as a way to

break the Microsoft monopoly (didn’t work)

=> huge amounts of money involved=> major corporate politics/warfare

(Sun & Netscape vs. Microsoft)

Page 6: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

6

Beyond the Hype (and loss thereof)

Not much fundamentally new here – we have seen almost all the concepts in other

languages before

But, its fairly well designed– more than can be said for a lot of things– Its better than C++ for many/most uses – It was built by someone who knew the

"landscape" of programming languages and has some taste

Page 7: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

7

Beyond the Hype (and loss thereof)

In my opinion its the best current language with wide platform support (backing of many solid implementations)

Page 8: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

8

Goals

Downloadable into a wide range of devices/platforms

Good OO language to replace C++ – Relatively small/simple/clean language– Camouflaged as C++ for sneak attack

when C++ was the dominant language C++ programmers will feel at home

Lots of checking and safety

Page 9: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

9

Major differences from C++

Generally simplified No pointers

– Actually everything is a pointer (reference), but their are no dangling pointers!

– No pointer dereferencing (where you used to say "->" you now always use ".")

Garbage collection added – Big big win

Page 10: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

10

What's been added from C (all in C++)

O-O concepts & information hiding Stronger typing Real constants (not just macros) Overloading (two functions with the

same name, but different parameter types)

New comment style ("//" to eol)

Page 11: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

11

What's been added beyond C++

More checking Exceptions (they were in C++, but..) (Limited) signature based typing

("interfaces" -- a big win) Runtime type identification (plus

other reflection capabilities) Built in threads and synchronization

Page 12: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

12

What's been added beyond C++ (cont.)

Packages (collections of classes in a namespace)

Dynamic runtime loading Strings (as objects) A root class (Object) Unicode characters (16 bit chars) 64 bit longs, bytes, booleans

– (literals true and false)

Page 13: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

13

What's been added beyond C++ (cont.)

A (small) container library (hashtables, etc.)

Special "doc" comments /** ... */ + post-processing to produce hyperlinked API documentation – html + special @directives in the

comments

Page 14: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

14

Things that are missing (but we probably won't miss):

Virtual functions (everything is virtual!)

Virtual base classes Virtual destructors Implicit constructor invocation (and

other constructor/destructor weirdness)

Page 15: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

15

Things that are missing (but we probably won't miss):

Arcane type conversion rules (and generally loose typing)

16 different meanings for const extern (now have strong load-time

checking) ->* operator (member pointers) :: (scope operator)

Page 16: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

16

Things that are missing (but we probably won't miss):

void * Null terminated strings Declaration vs. definition (always

done together, need not declare before use)

(Brain dead) multiple inheritance Templates

Page 17: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

17

Things that are missing (but we probably won't miss):

Operator functions Macros, include files, and

conditional compilation (the preprocessor)

Page 18: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

18

Other things that are missing (that we might miss): Independent functions Pointers to functions Default parameters Unsigned types Bare metal performance(?)

Page 19: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

19

So is it too slow?

Can get roughly 4x of C code performance (on many things you care about) using JIT compilers

Plenty fast for interactive apps– Spend a lot of time in native drawing code

anyway

Faster development time => more optimization time => faster code!

Page 20: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

20

More details on differences with C++ Lexical level

Designed to look almost exactly like C++ (which is almost identical to C)

Minor differences, but not worth mentioning

Page 21: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

21

More details on differences with C++ Syntactic level

Designed to look a lot like C++ – which was designed as a superset of C– but cleaned up most egregious parts

Changes: – inheritance syntax– initialization in constructors– split definition vs. declaration (and scope

operator) – protection declaration

Page 22: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

22

More details on differences with C++Control Flow All C/C++ flow control constructs

except goto– added labeled break and continue to

handle the few remaining legit uses– if/else for while do/while switch/case/break – return break continue

throw try/catch/finally to support exceptions

Page 23: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

23

Exception syntax

try { …throwable except = new my_exception();throw(except); …

} catch (my_exception ex) {… do something to recover …} catch (Exception ex) { … }finally {

… code that is always executed …}

Page 24: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

24

More details on differences with C++Control Flow (cont.) Now have real booleans

– can't test integers and pointers directly – "if (ptr)" must be "if (ptr != null)"

Page 25: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

25

Classes

The major construct in Java (like most object oriented languages) is the class.

Classes are a type definition: They define the data and operations of an object. – You can create several instances of

objects; several things with that data and those operations

Page 26: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

26

Classes

For C programmers you can think of this for now as a struct with the functions operating on the struct "inside" the struct.

For C++ programmers you can think of this as a class.

Page 27: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

27

class point_list { int x; int y; point_list next; double distance_to(point_list other) { double dx, dy; dx = (double)(x - other.x); dy = (double)(y - other.y); return Math.sqrt(dx*dx + dy*dy); } double distance_to_next() { if (next == null) return 0; else return distance_to(next); }}

Page 28: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

28

What have we got here.

Three instance variables– C++ == fields

Two methods– C++ == member functions– Note: There are no functions in Java, just

methods (notice that we had to say Math.sqrt() to get a square root).

Page 29: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

29

What have we got here.

If we had two points: pt1 and pt2, then we could compute the distance between them aspt1.distance_to(pt2)

Except... we have some problems here what are they? (p, v, c, after)

Page 30: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

30

Problem #1: self containment

Looks like a point_list contains a point_listclass point_list {...point_list next;

But, recall everything is a pointer, so this is a pointer (reference) to a point_list, so we are ok

Page 31: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

31

Like C++ Two forms of data: primitive and objectsPrimitive types:byte 8 bit signed integershort 16 bit signed integerint 32 bit signed integerlong 64 bit signed integerboolean true of falsechar 16 bit unicode characterfloat single precisiondouble double precision

Page 32: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

32

If its not a primitive its an object

Note: this includes strings & arrays Declaring instance variables of

object types actually declares references to objects of that class– null is a possible value– need to be initialized to refer to object

Referenced with “.” instead of “->”(back to problems)

Page 33: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

33

Problem #2: Visibility

Classes also provide information hiding and the default is to not allow full access to instance variables or methods.

So a better version would be...

Page 34: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

34

public class point_list { protected int x; protected int y; protected point_list next; public double distance_to(point_list other) { double dx, dy; dx = (double)(x - other.x); dy = (double)(y - other.y); return Math.sqrt(dx*dx + dy*dy); } public double distance_to_next() { if (next == null) return 0; else return distance_to(next); }}

Page 35: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

35

Specifying protection Members can be: public protected

private

<unlabeled>

Accessible to all

Accessible to classes within the same package and subclasses

Accessible only within the class itself

Inside package: protected

Outside package: private(no subclass access outside package).

Page 36: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

36

Specifying protection Classes can be: public, unlabeled, or private Almost all classes are public

(anybody can use them) Can have private or local classes

– only accessible in package– rare– can protect constructors instead

Page 37: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

37

Point of style

Its a good idea for all but the simplest classes to not have any public instance variables.– Instead have a protected variable with

read and write access methods. – This lets you change your mind later

without breaking all the code that uses yours.

Page 38: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

38

Point of style

protected int _x; public int x() {return _x;} public void set_x(int val)

{_x = val;} Seems tedious, but…

This has saved my sorry butt many times! (back to problems)

Page 39: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

39

Problem #3: no constructor

Haven't provided a way to create any useful objects of this type

Java initializes instance variables: int et al. 0

boolean false

float, double 0.0

char ‘\0’

Object null

Page 40: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

40

Initialization

You can also explicitly initialize instance vars

protected int x = 0; protected int y = 0; protected point_list next = null;

Page 41: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

41

Declaring constructors

Typically, you want provide a constructor. – If you don't provide a constructor, one

(that does nothing and takes no parameters) will be provided for you.

Constructor looks like a method with the same name as the class but no return type:

Page 42: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

42

Declaring constructors

public point_list( int xv, int yv, point_list nxt) { x = xv; y = yv; next = nxt; }

Page 43: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

43

Declaring multiple constructors

Often want to provide several constructors– Java does not do default parameters

public point_list(int xv, int yv) { this(xv,yv, null); } public point_list() { this(0,0); }

Page 44: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

44

Declaring multiple constructors

Notice that we can "chain" constructors together using "this()". – We can also invoke the super class

constructor using "super()". – Must be the first thing in the constructor.

(back to problems)

Page 45: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

45

Some misc. basics

All parameters are pass-by-value. – However, for all object types we are

passing references by values, so...

Can return at most one value. Arithmetic, etc. operations

(precedence, etc.) are the same as C/C++, except...

Page 46: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

46

Some misc. basics

Arithmetic, etc. operations are the same as C/C++, except... – Use of comma operator is limited to for

statements. – Can apply bitwise operations to booleans

(but not mixed int/boolean) to get non-shortcutting operations.

– == and != mean "refer to the same object".

Page 47: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

47

Some misc. basics

Like C++ can declare variables anywhere a statement is legal– including inside parens of for statements

Same scoping rules– scope limited to enclosing block: {... }

Don't have to declare before use.

Page 48: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

48

Hierarchical Types and Inheritance

The big wins in object-oriented programming come from hierarchical typing and inheritance.

Page 49: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

49

Hierarchical Types and Inheritance

Two things of importance:– Inheritance: the ability to derive the

implementation of something from some existing code (AKA getting someone else to do the work for you).

– Substitutability: the ability to write code that doesn't care about exactly what type it operates over (so you can substitute related but different types).

Page 50: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

50

Inheritance

In Java (like most OO languages) you can base the implementation of a class on another class. – Basically, you take what is in the other

class (the base or superclass) and then extend it to do new and/or different things.

– The new class (the derived class or subclass) preserves the API of the superclass

Page 51: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

51

Inheritance

The new class preserves the API of the superclass– so it does everything the superclass did

Consequently, an instance of a subclass can be substituted for an instance of a superclass– a variable that references the superclass

can safely be used to reference the subclass

Page 52: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

52

Declaring inheritance in class declarations Suppose we wanted to create a

colored_point_list which keeps a color value with each point...

Page 53: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

53

Declaring inheritance

public class colored_point_list extends point_list {

protected Color _pt_color; public Color pt_color() {return _pt_color;} public void set_pt_color(Color val) {_pt_color = val;}

public colored_point_list( int xv, int yv, point_list nxt, Color clr) { super(xv,yv,nxt); set_color(clr); }}

Page 54: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

54

Declaring inheritance

Note the extends clause– Gives the base class we are derived from– If there is no extends clause we

automatically inherit from Object (the Java root class).

– Java only supports single inheritance, so you only get to list one thing.

Page 55: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

55

Declaring inheritance

Note also that we call the superclass constructor (might as well let them do the work here) using the special form:"super(...);"

Like "this()" this must be the first thing in the constructor.

Page 56: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

56

Get substitutability

If we have a piece of code which declares a variable of type point_list, we can safely let it operate on an object of type colored_point_list.

Page 57: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

57

Another (different) use of “Super”

Can use “super” to refer to a method in the superclass that has been overridden by the subclass

public class grid8_point_list extends point_list { public void set_x(int val) { int rounded = (val / 8)*8 + ((val%8 >= 4)?1:0); super.set_x(rounded); } ...}

Page 58: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

58

Notes on this example

public class grid8_point_list extends point_list { public void set_x(int val) { int rounded = (val / 8)*8 + ((val%8 >= 4)?1:0); super.set_x(rounded); } ...}

Boy it’s a good thing we put that set_x() in there

We call set_x() don’t set x directly

Page 59: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

59

This Sometimes you need to refer to the

object itself in one of its methods (pass it somewhere). – Reserved word this is used for this purpose.

As in:

manager.put_in_table(this);

Note that instance variable references such as "_x" above are really shorthand for "this._x".

Page 60: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

60

Abstract classes

Its not necessary to completely define a class – This is useful to define the API to

something without requiring a particular implementation (see also interfaces).

– This is useful also if you have a lot of common functionality to put in a base class but details (i.e., implementation of particular methods) have to be provided by various subclasses.

Page 61: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

61

Abstract classes

(Must) declare the class "abstract" Declare each missing method

“abstract” and put a semicolon where the body would be.

abstract public class stack { abstract public void push(Object obj); abstract public Object pop(); abstract public boolean empty();}

Page 62: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

62

Abstract classes

Can't instantiate an abstract class (but can declare variables).

Page 63: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

63

Interfaces

Syntactically an interface declaration looks a lot like a class declaration (replace "class" with "interface"). – But, no variables and methods don't have

bodies.

Basically interfaces define an API, but no implementation

Page 64: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

64

Interfaces

Interfaces are used as a "promise". – Class can say:

"implements”interface_name" after extends clause

– This means that the class promises to implement the API of the interface.

– It doesn't say anything about how its going to do it, just that it will

– The compiler checks that it does.

Page 65: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

65

Interfaces

Can inherit from (“implement”) multiple interfaces.

Page 66: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

66

Substitutability for interfaces Can declare variables and parameters

with interface types – Variable can then refer to object of any type

that implements the interface Has promised to implement the API (&

compiler has checked) so this is completely type safe!

– Gives you a lot of flexibility to reimplement, etc.

– Advice: use this whenever you can

Page 67: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

67

Packages

Classes are organized into collections of related things– what constitutes one package is entirely

up to you.

Each source file belongs to a particular package – listed at the top with the package

declaration: package sub_arctic.lib;

Page 68: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

68

Packages

Note: its possible to leave the package declaration out which indicates the special "unnamed package”– don't do this! it just gets confusing to

everyone concerned

Page 69: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

69

Packages Package names have multiple parts

(‘subpackages”) separated by "." – java.awt and java.awt.image

But, these don't have a special relationship between them

Packages are primarily to segregate the name space– class names must be unique within the

package, but not across all packages

Page 70: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

70

Packages

Also have an effect on protection rules – recall: protected members can be

accessed by classes in same package

Page 71: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

71

Imports

You can use package names to disambiguate types.

Recall we had an example that used the class Color. – Comes from the library package java.awt

and its full name is java.awt.Color. – If you get tired of writing out the full name,

you can "import" the class: import java.awt.Color;

Page 72: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

72

Imports If you get two classes with the same

name from different packages you use full names to disambiguate.

Since compiler knows how to find packages, this eliminates the need for #includes– you can also import from compiled code

without the source!)

Page 73: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

73

Packages

java.lang.* is imported automatically.

Page 74: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

74

Static members

Instance variables belong to (have a copy in) each instance.

Can also declare variables that belong to the whole class. – Do this with static:

class a_class { protected static int count = 0; public a_class() {count++;} }

Page 75: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

75

Static members

There is only one copy of the static variable– belongs to the class (shared by all

instances).

You can also have static methods. – These can be invoked without an instance

(using the class name): Math.sqrt(3.1415d)

Page 76: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

76

Initialization of statics You can use conventional initializers

(after =) – Executed when the class is loaded

Also have special static initialization blocks (outside of methods): static {... some code ...}– Also executed when class is loaded– Java loader takes care of loading classes

you depend on first

Page 77: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

77

Final members

You can declare classes, methods, and variables final. – For variables this means they can't be

assigned to after initialization (AKA constants):

public static final double PI2 = Math.PI*Math.PI;

– For methods, this means you cannot override the method in subclasses.

– For classes this means all the methods are final.

Page 78: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

78

Final members

You can declare final variables in interfaces

Java idiom: to collect a bunch of reusable constants together put them in an interface and "implement" them in the classes where they are used.

Page 79: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

79

Strings

In Java, strings are objects of class String– not array's of char, although there are

operations to get back and forth– Special literal e.g: "abc" represents a

String object.

Character escapes such as \n similar to C.

Page 80: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

80

Strings

Strings are immutable– operations create new strings, don't

modify existing ones.

"+" is used for string concatenation, and is treated specially – Any + with at least one String operand is

treated as string concatenation – The other operand is converted to a string

(this also works for String parameters)

Page 81: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

81

Conversion to Strings

For primitive types there is a standard (and obvious) conversion

For Objects, the toString() method is called – Object provides one (prints class name

and unique id) – Or you can override

Page 82: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

82

Arrays

Arrays are also objects in Java

Can declare as "int foo[]" or "int[] foo" – both declare a variable which refers to an

array of ints (initialized to null)

Page 83: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

83

Arrays

Array size is not part of the type– that gets established by the instance

int[] foo = new int[52];...foo = new int[42]

Each array object has a read-only field: length foo.length == 42

Page 84: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

84

Arrays Note that arrays are collections of

Object references. – All set to null by default.

Can initialize arrays to refer to particular object with special form similar to C/C++ int[] foo = {3, 5, 9};Object[] bar = {"one", new Stack(), new Integer()};

Page 85: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

85

Array types

Arrays are hierarchically typed If sub is a subclass of base then sub[] is a subclass of base[]

So you could have: base[ ] base_var = new sub[42];

Page 86: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

86

Checking types at runtime

Can determine if an object qualifies as a particular type at runtime using expression: "obj instanceof aclass"

– "null instanceof aclass" is always false.

Page 87: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

87

Checking and converting types at runtime

Can convert to a sub- or super-class with a C style cast expression: "(aclass)expr" – Does runtime type check and throws an

exception if this is not a legal conversion (i.e., object being cast is not of that type or a subclass thereof).

Page 88: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

88

Output to stdout

java.lang.System has lots of useful stuff for accessing the local environment including: – System.out, System.err, and System.in

(for stdout, stderr, and stdin). – Two operations of particular interest:

System.out.print() and System.out.println() print anything convertible to a string with or without a newline.

Page 89: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

89

Threads

Threads are built into the language Concurrent threads can greatly

simplify program structure and design for a number of things

Page 90: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

90

Threads

They also make testing and debugging nearly impossible

So unless your programs all work without testing (and/or there is no reasonable way around it), I advise: Just say no!

Page 91: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

91

Threads

Note: if you feel compelled to use threads with subArctic read that section in the manual! – non-obvious things you have to do or you

will get (nasty & hidden!) concurrency bugs

Page 92: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

92

Good luck...

... and, as always, if you or any of your programming team are caught or killed, I will disavow that I ever taught you anything about Java.

Page 93: A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

93