Docsity

Java Programming Language: CMSC 433 Lecture Notes by Alan Sussman, University of Maryland , Study notes of Programming Languages

Toggle sidebar
bg1
CMSC 433, Alan Sussman, U. Maryland
(via Bill Pugh) 1
CMSC433, Spring 2001
Programming Language
Technology and Paradigms
Basic Java
Alan Sussman
September 17, 2001
CMCS 433, Fall 2001 -Alan Sussman 2
Administrivia
•C++ project due Thursday, 6PM
•We have a TA -Yu-Lin (Tristan) Wen
–email and office hours posted
•Java project posted soon
–a simple Web server
–due Wednesday, Oct. 3
•Java readings from Thinking in Java
–we’ll do parts of many chapters, but definitely read
Chapter 1 for an overview
–I’ll add some suggestions on Web page, but use it as a
reference
CMCS 433, Fall 2001 -Alan Sussman 3
Last time
•Casts
–static, dynamic, const, reinterpret
•Chaining
–for calls to void and copy constructors, operator=
•Namespaces
–to help alleviate name clash problems
•Exceptions
–are like objects, and can be thrown/caught
CMCS 433, Fall 2001 -Alan Sussman 4
What Makes Java Different
•Java fully specified
–e.g., constants, size of types, array bounds
checking, no dangling pointers
–language specification intended to completely
specify the behavior of all programs
•not just correct ones
•all runtime errors must be caught
–KISS principle applied
•many useful, but not essential, features from C++
not included (operator overloading, templates,
multiple inheritance, standalone functions, …)
CMCS 433, Fall 2001 -Alan Sussman 5
Java semantics
•Machine architecture insensitive
–size of machine word
–floating point format (must use IEEE 754)
–big/little-endian
•Compiled to machine independent byte
code
•Many C++ programs break when moved to
machine with different word size or
endianness
CMCS 433, Fall 2001 -Alan Sussman 6
Java security
•Can strictly limit access to code
–untrusted code can’t access files and are
limited in network connectivity by default
•Compiled code (byte codes) can be verified
for correctness (by another program)
•But security bugs are still possible
–e.g., denial of service, insecure mode code
–but all C++ programs run in an insecure mode
pf3
pf4
pf5

Partial preview of the text

Download Java Programming Language: CMSC 433 Lecture Notes by Alan Sussman, University of Maryland and more Study notes Programming Languages in PDF only on Docsity!

CMSC 433, Alan Sussman, U. Maryland

CMSC433, Spring 2001

Programming Language

Technology and Paradigms

Basic Java

Alan Sussman

September 17, 2001

CMCS 433, Fall 2001 - Alan Sussman 2

Administrivia

  • C++ project due Thursday, 6PM
  • We have a TA - Yu-Lin (Tristan) Wen
    • email and office hours posted
  • Java project posted soon
    • a simple Web server
    • due Wednesday, Oct. 3
  • Java readings from Thinking in Java
    • we’ll do parts of many chapters, but definitely read Chapter 1 for an overview
    • I’ll add some suggestions on Web page, but use it as a reference

CMCS 433, Fall 2001 - Alan Sussman 3

Last time

  • Casts
    • static, dynamic, const, reinterpret
  • Chaining
    • for calls to void and copy constructors, operator=
  • Namespaces
    • to help alleviate name clash problems
  • Exceptions
    • are like objects, and can be thrown/caught

CMCS 433, Fall 2001 - Alan Sussman 4

What Makes Java Different

• Java fully specified

  • e.g., constants, size of types, array bounds checking, no dangling pointers
  • language specification intended to completely specify the behavior of all programs - not just correct ones - all runtime errors must be caught
  • KISS principle applied
    • many useful, but not essential, features from C++ not included (operator overloading, templates, multiple inheritance, standalone functions, …)

CMCS 433, Fall 2001 - Alan Sussman 5

Java semantics

• Machine architecture insensitive

  • size of machine word
  • floating point format (must use IEEE 754)
  • big/little-endian

• Compiled to machine independent byte

code

• Many C++ programs break when moved to

machine with different word size or

endianness

CMCS 433, Fall 2001 - Alan Sussman 6

Java security

• Can strictly limit access to code

  • untrusted code can’t access files and are limited in network connectivity by default

• Compiled code (byte codes) can be verified

for correctness (by another program)

• But security bugs are still possible

  • e.g., denial of service, insecure mode code
  • but all C++ programs run in an insecure mode

CMSC 433, Alan Sussman, U. Maryland

CMCS 433, Fall 2001 - Alan Sussman 7

Java features

• Strong type system

• Multi-threading and synchronization

• Garbage collection

• Exceptions

• class Class

  • classes are objects too

• class Object

  • the class all classes are derived from

CMCS 433, Fall 2001 - Alan Sussman 8

Java libraries

  • Utilities
    • collection classes, Zip files, internationalization
  • GUIs, graphics and media
  • Networking
    • sockets, URLs, RMI, CORBA
  • Threads
  • Databases
  • Cryptography/security

CMCS 433, Fall 2001 - Alan Sussman 9

Java Basics

• Mostly C++ syntax

• Statements

  • empty, expressions, blocks {}
  • control flow (if, switch, while, for, …)
  • throw and try/catch/finally
  • synchronized
  • no goto

CMCS 433, Fall 2001 - Alan Sussman 10

Expressions

• Mostly C/C++ syntax

• Standard math operators: +, -, *, /, %

• Bit operations: &, |, ^, ~, <<, >>, >>>

• Update ops: =, +=, -=, *=, /=, …

• Relational ops: <, <=, ==, >=, >, !=

• Boolean ops: &&, ||,!

• Conditional expression: b? e1 : e

CMCS 433, Fall 2001 - Alan Sussman 11

Class operations

• Select method/variable/class/subpackage:.

• Class operators: new, instance, (Class)

• No pointer operations: *, &, ->

CMCS 433, Fall 2001 - Alan Sussman 12

Hello World example

public class HelloWorld { public static void main(String [] args) { if (args.length == 1) System.out.println(“Hello “ + args[0]); else System.out.println(“Hello world”); } }

CMSC 433, Alan Sussman, U. Maryland

CMCS 433, Fall 2001 - Alan Sussman 19

More Object operations

• (Bar) foo

  • run-time exception if type of the object referenced by foo is not a subclass of Bar
  • compile-time error if Bar is not a subtype of foo (i.e. it always throws an exception)
  • doesn’t transform anything, just allows treating the result as if it were of type Bar

CMCS 433, Fall 2001 - Alan Sussman 20

Arrays

• a special kind of object (with lots of syntax)

• can declare arrays of any type

• have one instance variable: length

• also have contents indexed with a subscript

from 0 … length-

• can be initialized using {val 0 ,val 1 , …, valn}

notation

  • inefficient for large arrays

CMCS 433, Fall 2001 - Alan Sussman 21

Array declarations

  • Little surprising for C/C++ programmer
  • int[] A and int A[] have identical semantics
    • declares A to be a variable containing a reference to an array of ints
  • int[] A[], B;
    • A is a ref to an array of refs to arrays of ints
    • B is a ref to an array of ints
  • None of these allocate an array
  • A = new int [10]; allocates an array of 10 ints, and makes A be a reference to it CMCS 433, Fall 2001 - Alan Sussman 22

Array example

int[] array1 = {1, 3, 5}; int[][] a = new int[10][3]; // a.length == 10 // a[7].length == 3

a[5][2] = 42; a[9] = array1; // a[9][2] == 5

// use of array initializers int[][] twoD = {{1, 2, 3}, {4, 5}, {6}}; Object [] args = {“one”, “two”, a}; main(new String [] {“a”, “b”, “c”});

CMSC433, Spring 2001

Programming Language

Technology and Paradigms

Basic Java, continued

Alan Sussman

September 20, 2001

CMCS 433, Fall 2001 - Alan Sussman 24

Administrivia

• C++ project due today, 6PM

  • turn in something on time, even if you keep working until 6AM
  • your grade will be the higher of the on-time submission and 80% of the late submission

• Java project posted later today

  • web server will be up and running for testing soon
  • we’ll talk about it more on Tuesday

CMSC 433, Alan Sussman, U. Maryland

CMCS 433, Fall 2001 - Alan Sussman 25

Last time

  • Java basics
    • statements, expressions
    • naming conventions
    • values are either object references or primitive types
  • Objects
    • all dynamically allocated
    • only accessed through, and can contain, object references
    • many special object operations available
      • =, ==, equals(), toString(), clone(), getClass(), instanceOf
  • Arrays
    • objects with a length instance variable
    • array name is a reference to the array object

CMCS 433, Fall 2001 - Alan Sussman 26

String

• A class for representing non-mutable strings

• string constants converted to String

• + does string concatenation

• In some contexts objects automatically

converted to String type

• Example:

public static void printArray(Object [] a) { for (int i = 0; i < a.length; i++) System.out.println(“a[“ + i + “] = “ + a[i]); }

CMCS 433, Fall 2001 - Alan Sussman 27

Object/memory allocation

  • Only way/time an object gets allocated is:
    • by executing new
      • one object per invocation of new
    • by having an array constant (e.g., {5, -5, 42})
    • by having a string constant (e.g.,“Hello world”)
  • Declaring a reference variable does not allocate an object
  • Allocating an array does not automatically allocate the contents of the array CMCS 433, Fall 2001 - Alan Sussman 28

Allocation (cont.)

• Multi-dimensional array allocation

  • int [][] a = new int [10][10];
  • equivalent to, but faster than: int [][] a = new int [10][]; for(int i=0; i<10; i++) a[i] = new int[10];

• No explicit deallocate required, nor allowed

CMCS 433, Fall 2001 - Alan Sussman 29

Garbage collection

• Java uses garbage collection to find objects

that cannot be referenced

  • i.e. do not have any pointers to them

• GC not a major performance bottleneck

  • fast garbage collectors have been implemented
  • on many commercial systems, GC runs on a single processor of a multiprocessor

CMCS 433, Fall 2001 - Alan Sussman 30

Other notes

  • Forward references resolved automatically
    • can refer to method/variable defined later
  • Integer division by zero raises an exception
  • Integer overflow drops extra bits
  • Floating point errors create special values
    • NaN, POSITIVE_INFINITY, …
  • Separate name spaces for methods, classes, variables, … - can produce confusing error messages

CMSC 433, Alan Sussman, U. Maryland

CMCS 433, Fall 2001 - Alan Sussman 37

Class details

  • Method names can be overloaded
    • method invoked is determined by both its name and the types of the parameters
    • resolved at compile-time, based on compile-time types
  • Methods can also be overridden
    • define a method also defined by a superclass
    • arguments and result types must be identical
    • resolved at run-time, based on type of object method is invoked on

CMCS 433, Fall 2001 - Alan Sussman 38

Classes and methods

  • this refers to the object the method is invoked on
  • super refers to the same object as this
    • but used to access methods/variables in superclass
  • Methods
    • can be declared in both classes and interfaces
      • only implemented in classes
    • must have a return type
      • except constructors
      • void can be used only as a return type
    • references to objects or arrays can be returned

CMCS 433, Fall 2001 - Alan Sussman 39

Instance variable / method modifiers

• Visibility/access

  • public – visible everywhere
  • protected – visible within same package or in subclass
  • package (default) – visible within same package
  • private – visible only within this class

• static – a class method or variable

CMCS 433, Fall 2001 - Alan Sussman 40

Instance variable modifiers

• transient – not stored when object

serialized

• volatile – don’t assume the variable hasn’t

changed since the last time it was accessed

  • might be modified by another thread that doesn’t have a lock on the object

• final – can’t be changed; must be initialized

in declaration or in constructor

CMCS 433, Fall 2001 - Alan Sussman 41

Method modifiers

  • abstract – no implementation provided
    • class must be abstract
  • final – this method cannot be overridden
    • useful for security
    • allows compiler to inline method
  • native – implemented in another language
  • synchronized
    • locks object before method is executed
    • lock released after method finishes

CMCS 433, Fall 2001 - Alan Sussman 42

Method arguments

• Only pass-by-value

  • but object parameters are references to heap objects that can be changed

• Only arguments used to distinguish methods

  • not return types

• Syntax same as C/C++