Docsity

Notes on A Crash Course in Java | CMSC 433, Study notes of Programming Languages

Partial preview of the text

Download Notes on A Crash Course in Java | CMSC 433 and more Study notes Programming Languages in PDF only on Docsity!

http://www.cs.umd.edu/~pugh/java/crashCourse

What Makes Java Different

Day 1, Session 1

What makes Java Dif ferent

  • Java is specified

2

  • KISS principle applied
  • Semantics are architecture insensitive
  • Safe/Secure
  • A modern programming language
  • Fewer bugs?
  • Libraries Galore!
  • Speed
  • The Hype

Java is specified

  • Pascal/C/C++ isn’t
    • 1000*
    • (-5)/
    • int^ a[10];^ for(int^ i=0;i<=10;i++)^ a[i]^ =^ 0;
    • delete^ p;^ q^ =^ new^ foo();^ x^ =^ p->key;^ p->key^ =^ 0;
    • *(int^ *)(random())^ =^0

3

  • The Java specification (is intended) to completely

specify the behavior of all programs

  • Not just “correct” programs
  • Caveat - multi-threading, random numbers, ...
    • specified but has multiple valid implementations
  • All run-time errors must be caught
  • Can make promises about what might happen

KISS principle applied

  • Many useful features were removed from C++
    • Makes language easier to learn and implement
    • operator overloading
    • user-definable coercions
    • templates
    • multiple inheritance
      • multiple supertypes still allowed
    • structs/unions
    • unsigned integers
    • stand-alone functions

4

  • Not essential

Security Risks

  • If you run an program in an insecure mode
    • It can do anything you can do
    • It can set up a spy to watch what you do

7

  • This includes
    • Erase your hard disk
    • Shut down your computer
    • Infect you with a virus
    • Make your Internet connection dial long distance
    • Add some Quicken wire transfers
  • All C/C++ programs run in an insecure mode
  • Signed code -- A solution?

Signed code -- A solution?

  • Provides "proof" of who wrote the code
    • You might trust big companies
    • Allow you to track down perpetrators

8

  • Can be signed by third parties
  • If a web page erases your hard disk
    • allows you to easily determine who did it
    • but subtle attacks might be hard to catch
  • No protection against bugs
    • or malicious exploitation of bugs
  • Active-X and Java code can be signed
  • Privileges bestowed to signed code

Privileges bestowed to signed code

  • You can set policies about which signatures give

what privileges

9

  • In Active-X, all or nothing
  • In Java
    • version 1.1 - applet sandbox or full power
    • version 1.2 - finer control

A modern programming language

  • Includes many features that PL researchers have

been advocating for years (but never caught on in

mass-market)

  • strong type system
  • multi-threading and synchronization
  • garbage collection
  • exceptions
  • class Class
  • class Object

10

  • Not an embarrassment to academic CS
  • Adapts ideas from: C++, Smalltalk, Lisp, Modula-3,

Objective-C

13

Speed

  • Initial JVM’s are slow, but situation has improved
  • JVM’s that do Just-in-time compilation
  • Native code compilers
    • need to allow for dynamically loaded code
  • Byte code optimizers, shrinkers and obsfucators
  • Sun’s Hotspot JVM
  • How bad is it really?

How bad is it really?

  • Prime number sieve - primes less than 100,
    • Sun Solaris JDK 1.1.6^ 70 seconds
    • Sun Solaris JDK 1.2beta3/JIT^ 27 seconds
    • Sun Solaris gcc -O4^ 21 seconds

14

  • Developers use a different coding style for Java
    • Lots of little methods/objects, run-time type dependent stuff
    • This is a good thing; better programmer productivity?
    • But makes it hard to generate efficient code

The Hype

  • Cover of Businessweek !?!?
  • Incredibly important to where Java is today

15

  • good tools
  • wide availability of tools and support
  • lots of libraries
  • excessive hype
  • overhype backlash
  • C++ was born in the early 80’s
  • took a decade to mature
  • The downside
  • Hasty decisions have been cast in stone
  • A number of poor designs exist in the libraries
  • difficult to fix without breaking code
  • Religion, heat and flames

This slide intentionally left blank

16

Mostly C/C++ syntax: statements

  • Empty statement, expression statement

19

  • blocks { ... }
  • if, switch, while, do-while, for
  • break, continue, return
    • any statement can be labeled
    • break and continue can specify a label
    • continue must specify a loop label
  • throw and try-catch-finally
  • synchronized
  • No goto

Mostly C/C++ syntax: expressions

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

20

  • Bit operations: &, |, ^, ~, <<,>>, >>>
  • *Update operators: =, +=, -=, =, /=, %=, ...
  • Relational operations: <, <=, ==,>=,>, !=
  • Boolean operations: &&, ||,!
  • Conditional expressions: b? e1 : e
  • Select methods/variables/class/subpackage:.
  • Class operators: new, instanceof, (Class)
  • *No pointer operations: , &, ->

Hello World example

public class HelloWorldApplication { public static void main(String [] args) { if (args.length == 1) System.out.println("Hello " + args[0]); else System.out.println("Hello World"); } }

21

Naming conventions

  • Classes/Interfaces start with a capital letter

22

  • packages/methods/variables start with a lowercase

letter

  • ForMultipleWords, capitalizeTheFirstLetterOfEachWord
  • Underscores_discouraged
  • CONSTANTS are in all uppercase

String Example

25

String a = "π!=pie";

String b = a.substring(2,4);

String count

offset

value

6

0

String count

offset

value

2

2

a

b char [ ]

length^6

0 1 2 3 4 5 π! = p i e

Object operations

  • = assignment
    • For object references: copies reference, not object

26

  • == equality test
    • For object references: true if references to same object
  • foo.equals(bar)
    • By default, same as ==, but can/should be overridden
  • foo.toString()
    • Returns String representation, can/should be overridden
  • More Object operations

More Object operations

  • foo.clone()
    • Returns a shallow copy of^ foo^ (not supported on all Objects)

27

  • foo.getClass()
    • Returns class of^ foo^ (result is of type^ Class)
  • foo^ instanceof^ Bar
    • true if objected referenced by^ foo^ is a subtype of class^ Bar
  • (Bar)^ foo
    • Run-time exception if the object referenced by^ foo^ is not a member of a subclass of Bar
    • Compile-time error if^ Bar^ is not a subtype of^ foo^ (i.e., if it always throws an exception)
    • Doesn’t transform anything just lets us treat the result as if it were of type Bar

Special Objects

  • Arrays

28

  • String

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

31

Array example

String

  • A class for representing non-mutable strings

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

  • “string constants” in program are converted into a

String

  • +^ does string concatenation
  • In some contexts, objects are automatically

converted to String type

  • More about strings later...

Object/memory allocation

  • The only way/time an object gets allocated is:
    • by executing new
      • One object per invocation of new
    • by having a array constant (e.g.,^ {5, -5, 42})
    • having a string constant (e.g.,^ "Hello^ World!")
    • Declaring a reference variable doesn’t allocate an object
    • Allocating an array doesn’t automatically allocate the contents of the array
    • multi-array creation^ 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];

33

  • No explicit deallocate is required/allowed

Garbage Collection

  • Java uses garbage collection to find objects that

cannot be referenced

  • (e.g., do not have any pointers to them)

34

  • Garbage collection not a major bottleneck
    • Faster Garbage Collectors coming
    • On existing commercial systems, GC runs on only a single processor

http://www.cs.umd.edu/~pugh/java/crashCourse

Object Oriented

Programming

Day 1, session 3

Objects, Classes and Interfaces

  • Java Objects, constructors, instance variables and

methods

38

  • Superclasses and Interfaces
  • public/protected/private methods
  • class methods and variables
  • final methods

Classes

  • Each object is an instance of a class
    • An array is an object

39

  • Each class is represented by a class object
    • (of type^ Class)
  • Each class extends one superclass
    • (Object^ if not specified)
    • except class^ Object, which has no superclass

More about Classes

  • Each class has an associated set of methods and

fields/variables

  • Variables hold primitive values or object references

40

  • Use ‘.’ to access object fields
    • variables and methods
    • e.g.,^ x.y(a.b)
  • Most methods are invoked using C++ virtual method

semantics

  • except static, private and final methods