A first look at java
This presentation is the property of its rightful owner.
Sponsored Links
1 / 86

A First Look At Java PowerPoint PPT Presentation


  • 99 Views
  • Uploaded on
  • Presentation posted in: General

A First Look At Java. Download as Power Point file for saving or printing . Outline. 13.2 Thinking about objects 13.3 Simple expressions and statements 13.4 Class definitions 13.5 About references and pointers 13.6 Getting started with a Java language system.

Download Presentation

A First Look At Java

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


A first look at java

A First Look At Java

Download as Power Point file for saving or printing.

Modern Programming Languages - Chapter 13


Outline

Outline

  • 13.2 Thinking about objects

  • 13.3 Simple expressions and statements

  • 13.4 Class definitions

  • 13.5 About references and pointers

  • 13.6 Getting started with a Java language system

Modern Programming Languages - Chapter 13


Java borrowed c syntax simple java program

Java borrowed C++ SyntaxSimple Java Program

public class ex1 {

public static void main(String args[])

{ System.out.println("Hello World");

}

}

Simple C++ Program

#include <iostream.h>

void main( void )

{ cout << "Hello World";

}

Modern Programming Languages - Chapter 13


Java c example

Java/C++ Example

class Stack {

private: double s[10];

int top;

public:

Stack() { top = -1; }

double pop() { return s[top--]; }

void push(double e){

s[ ++top ] = e; };

};

void main() {

Stack *s1 = new Stack();

s1->push(3.14);

s1->push(-13.0);

cout << s1->pop();

}

class Stack {

private double s[ ] = new double[10];

private int top;

public Stack() { top = -1; }

public double pop() { return s[top--]; };

public void push( double e ) { s[++top] = e; }

}

public class UseStack {

public static void main(String a[])

{Stack s1 = new Stack();

s1.push(3.14);

s1.push(-13.0);

System.out.print( s1.pop() );

}

}


Object oriented example

Object Oriented Example

  • Colored points on the screen

  • Data?

    • Coordinates

    • Color

  • Operations?

    • Move itself

    • Report its position

Modern Programming Languages - Chapter 13


3 point objects

3 PointObjects

Modern Programming Languages - Chapter 13


Java terminology

Java Terminology

  • Each point is an object

  • Each includes three fields

  • Each has three methods

  • Each is an instance of the same class

Modern Programming Languages - Chapter 13


Object oriented style

Object-Oriented Style

  • Class serves as template for data fields and implements operations

  • Object is instance of a class, essentially the memory storage allocated for field data

  • Eachobject independent of others

  • The class of an object determines the operations that can be performed on an object

  • Object field data can be limited to access only within methods implemented in the object’s class.

  • Object-oriented languages support information-hiding and data encapsulation.

Modern Programming Languages - Chapter 13


Java class definitions a peek

Java Class Definitions: A Peek


Point object an instance

Point Object - An Instance

  • A Point object is an instance of the Point class definition.

  • Each field of the object requires a memory allocation.

  • A simple view of the memory allocated for a Point object instantiation.

class Point {

int x, y;

Color myColor;

p

100

Point p = new Point( );

100

Modern Programming Languages - Chapter 13


Outline1

Outline

  • 13.2 Thinking about objects

  • 13.3 Simple expressions and statements

  • 13.4 Class definitions

  • 13.5 About references and pointers

  • 13.6 Getting started with a Java language system

Modern Programming Languages - Chapter 13


Primitive types we will use

Primitive Types We Will Use

  • Not classes, Java not a pure OOL

  • Scalars (i.e. simple, having only one value)

  • int: -231..231-1, written the usual way

  • char: 0..216-1, written 'a', '\n', etc., using the Unicode character set

  • double: IEEE 64-bit standard, written in decimal (1.2) or scientific (1.2e-5, 1e3)

  • boolean: true and false

  • Oddities: void and null

Modern Programming Languages - Chapter 13


Primitive types we won t use

Primitive Types We Won’t Use

  • byte: -27..27-1

  • short: -215..215-1

  • long: -263..263-1, written with trailing L

  • float: IEEE 32-bit standard, written with trailing F (1.2e-5, 1e3)

Modern Programming Languages - Chapter 13


Constructed types

Constructed Types

  • Constructed types are all reference types: they are references to objects

    • Any class name, like Point

    • Any interface name (Chapter 15)

    • Any array type, like Point[] or int[](Chapter 14)

Modern Programming Languages - Chapter 13


Strings

Strings

  • Predefined but not primitive: a class String

  • A string of characters enclosed in double-quotes works like a string constant

  • But it is actually an instance of the String class, and object containing the given string of characters

Modern Programming Languages - Chapter 13


A string object

A String Object

"Hello there"

"Hello there".length() is 11

"Hello there".charAt(7) is h

"Hello there".toUpperCase() is HELLO THERE

Modern Programming Languages - Chapter 13


Numeric operators

Java Expression

Java Expression

Value

Value

13.0*2.0

1+2*3

26.0

7

15.0/7.0

15/7

2.142857142857143

2

15%7

1

-(5*5)

-25

Numeric Operators

  • int: +, -, *, /, %, unary –

  • double: +, -, *, /, unary –

Modern Programming Languages - Chapter 13


Concatenation

Java Expression

Value

"123"+"456"

"123456"

"The answer is " + 4

"The answer is 4"

"" + (1.0/3.0)

"0.3333333333333333"

1+"2"

"12"

"1"+2+3

"123"

1+2+"3"

"33"

Concatenation

  • The + operator has special overloading and coercion behavior for the class String

Modern Programming Languages - Chapter 13


Comparisons

Java Expression

Value

1<=2

true

1==2

false

true!=false

true

Comparisons

  • The usual comparison operators <, <=, >=, and >, on numeric types

  • Equality == and inequality != on any type, including double (unlike ML)

Modern Programming Languages - Chapter 13


Boolean operators

Java Expression

Value

1<=2 && 2<=3

true

1<2 || 1>2

true

1<2 ? 3 : 4

3

Boolean Operators

  • && and ||, short-circuiting, like ML’s andalso and orelse

  • !, like ML’s not

  • a?b:c, like ML’s if a then b else c

Modern Programming Languages - Chapter 13


Operators with side effects

Operators With Side Effects

  • An operator has a side effect if it changes something in the program environment, like the value of a variable or array element

  • In ML, and in Java so far, we have seen only pure operators—no side effects

  • Now: Java operators with side effects

Modern Programming Languages - Chapter 13


Assignment

Assignment

  • a=b: changes a’s memory equal to b’s

  • Assignment is an important part of what makes a language imperative

  • Assignment is dangerous when aliases allowed as in Java

  • Aliases occur when multiple names reference a common memory location

  • Aliases allow side-effects by changes to a memory location through more than one name

Modern Programming Languages - Chapter 13


Rvalues and lvalues

Rvalues and Lvalues

  • Why does a=1 make sense, but not 1=a?

  • Expressions on the right must have a value: a, 1, a+1, f() (unless void), etc.

  • Expressions on the left must have memory locations: a or d[2], but not 1 or a+1

  • These two attributes of an expression are sometimes called the rvalue and the lvalue

Modern Programming Languages - Chapter 13


Rvalues and lvalues1

Rvalues and Lvalues

  • In most languages, the context decides whether the language will use the rvalue or the lvalue of an expression

  • A few exceptions:

    • Bliss: x := .y

    • ML: x := !y (both of type 'a ref)

Modern Programming Languages - Chapter 13


More side effects

Long Java Expression

Long Java Expression

Short Java Expression

Short Java Expression

a=a+1

a=a+b

a++

a+=b

a=a-1

a=a-b

a-=b

a--

a=a*b

a*=b

More Side Effects

  • Compound assignments

  • Increment and decrement

Modern Programming Languages - Chapter 13


Values and side effects

Java Expression

Value

Side Effect

a+(x=b)+c

the sum of a, b and c

changes value of x, making it equal to b

(a=d)+(b=d)+(c=d)

three times the value of d

changes values of a, b and c, making them all equal to d

a=b=c

the value of c

changes values of a and b, making them equal to c

Values And Side Effects

  • Side-effecting expressions have both a value and a side effect

  • Value of x=y is the value of y; side-effect is to change x to have that value

Modern Programming Languages - Chapter 13


Pre and post

Java Expression

Value

Side Effect

a++

the old value of a

adds one to a

++a

the new value of a

adds one to a

a--

the old value of a

subtracts one from a

--a

the new value of a

subtracts one from a

Pre and Post

  • Values from increment and decrement depend on placement

Modern Programming Languages - Chapter 13


Instances

Instances

  • A Point object is an instance of the Point class definition.

  • Each field of the object requires a memory allocation.

  • A simple view of the memory allocated for a Point object instantiation.

class Point {

int x, y;

Color myColor;}

:

Point p = new Point( );

100

100

p

Modern Programming Languages - Chapter 13


Instance method calls

Java Expression

Value

s.length()

the length of the String s

s.equals(r)

true if s and r are equal, false otherwise

r.equals(s)

same

r.toUpperCase()

A String object that is an uppercase version of the Stringr

r.charAt(3)

the char value in position 3 in the String r (that is, character 4)

r.toUpperCase().charAt(3)

the char value in position 3 in the uppercase version of the String r

Instance Method Calls

Require an object:

String s = new String();

String r = “Hello”;

Modern Programming Languages - Chapter 13


Class method calls

Java Expression

Value

String.valueOf(1==2)

"false"

Math.abs(-5);

5

String.valueOf(1.0/3.0)

"0.3333333333333333"

Class Method Calls

  • Class methods define things the class itself knows how to do—not objects of the class

  • The class just serves as a labeled namespace

  • Similar to ordinary function calls in non-object-oriented languages, no object required

Modern Programming Languages - Chapter 13


Instance versus class methods

Instance versus Class Methods

Instance method

Called with an instance. Example:

p.move( 4, 6);

Class method

Declared static, called with a class. Example:

Point.default();

import java.awt.Color;

public class Point {

private int x, y;

private Color myColor = Color.blue;

public int currentX() { return x; }

public int currentY() { return y; }

public void move(int newX, int newY) {

x = newX;

y = newY;

}

public static Color default() {

return Color.blue;

}

}

Modern Programming Languages - Chapter 13


Method call syntax

Method Call Syntax

  • Three forms:

    • Normal instance method call:

    • Normal class method call

    • Either kind, from within another method of the same class

<method-call> ::= <reference-expression>.<method-name>(<parameter-list>)

<method-call> ::= <class-name>.<method-name>(<parameter-list>)

<method-call> ::= <method-name>(<parameter-list>)

Modern Programming Languages - Chapter 13


Object creation expressions

Java Expression

Value

new String()

a new String of length zero

new String(s)

a new String that contains a copy of String s

new String(chars)

a new String that contains the char values from array

Object Creation Expressions

  • To create a new object that is an instance of a given class

  • Parameters are passed to a constructor—a special method of the class

<creation-expression> ::= new <class-name>(<parameter-list>)


No object destruction

No Object Destruction

  • Objects are created with new

  • Objects are never explicitly destroyed or deallocated

  • Garbage collection reclaims storage automatically for any inaccessible object (chapter 14)

  • Removes programmer memory management as source of errors

Modern Programming Languages - Chapter 13


General operator info

General Operator Info

  • All left-associative, except for assignments

  • 15 precedence levels

    • Some obvious: * higher than +

    • Others less so: < higher than !=

    • Use parentheses to make code readable

  • Many coercions

    • null to any reference type

    • Any value to String for concatenation

    • One reference type to another sometimes (Chapter 15)

Modern Programming Languages - Chapter 13


Numeric coercions

Java expression

value

'a'+'b'

195

1/3

0

1/3.0

0.3333333333333333

1/2+0.0

0.0

1/(2+0.0)

0.5

Numeric Coercions

  • Numeric coercions (for our types):

    • char to int before any operator is applied (except string concatenation)

    • int to double for binary ops mixing them

Modern Programming Languages - Chapter 13


Statements

Statements

  • That’s it for expressions

  • Next, statements:

    • Expression statements

    • Compound statements

    • Declaration statements

    • The if statement

    • The while statement

    • The return statement

  • Statements are executed for side effects: an important part of imperative languages

  • Modern Programming Languages - Chapter 13


    Expression statements

    Java Statement

    Equivalent English Command

    speed = 0;

    Store a 0 in speed.

    a++;

    Increase the value of a by 1.

    inTheRed = cost > balance;

    If cost greater than balance, inTheRed to true, otherwise to false.

    Expression Statements

    <expression-statement> ::= <expression> ;

    • Any expression followed by a semicolon

    • Value of the expression, if any, is discarded

    • Java does not allow the expression to be something without side effects, like x==y


    Compound statements

    Java Statement

    Equivalent English Command

    { a = 0; b = 1;}

    Store a zero in a, then store a 1 in b.

    { a++; b++; c++;}

    Increment a, then increment b, then increment c.

    { }

    Do nothing.

    Compound Statements

    <compound-statement> ::= { <statement-list> }< statement-list> ::= <statement> <statement-list> | <empty>

    • Do statements in order

    • Also serves as a block for scoping

    Modern Programming Languages - Chapter 13


    Declaration statements

    boolean done = false;

    Define a new variable named done of type boolean, and initialize it to false.

    Point p;

    Define a new variable named p of type Point. (Do not initialize it.)

    { int temp = a; a = b; b = temp;}

    Swap the values of the integer variables a and b.

    Declaration Statements

    <declaration-statement> ::= <declaration> ;<declaration> ::= <type> <variable-name> | <type> <variable-name> = <expression>

    • Block-scoped definition of a variable

    Modern Programming Languages - Chapter 13


    The if statement

    Java Statement

    Equivalent Command in English

    if (i > 0) i--;

    Decrement i, but only if it is greater than zero.

    if (a < b) b -= a;else a -= b;

    Subtract the smaller of a or b from the larger.

    if (reset) {  a = b = 0;  reset = false;}

    If reset is true, zero out a and b and then set reset to false.

    The if Statement

    <if-statement> ::= if(<expression>) <statement> | if(<expression>) <statement> else <statement>

    • Dangling else resolved in the usual way

    Modern Programming Languages - Chapter 13


    The while statement

    The while Statement

    <while-statement> ::= while(<expression>) <statement>

    • Evaluate expression; if false do nothing

    • Otherwise execute statement, then repeat

    • Iteration is another hallmark of imperative languages

    • (Note that this iteration would not make sense without side effects, since the value of the expression must change)

    • Java also has do and for loops

    Modern Programming Languages - Chapter 13


    While continued

    Java Statement

    Equivalent Command in English

    while (a<100) a+=5;

    As long as a is less than 100, keep adding 5 to a.

    while (a!=b) if (a < b) b -= a;else a -= b;

    Subtract the smaller of a or b from the larger, over and over until they are equal. (This is Euclid's algorithm for finding the GCD of two positive integers.)

    while (time>0) { simulate(); time--;}

    As long as time is greater than zero, call the simulate method of the current class and then decrement time.

    while (true) work();

    Call the work method of the current class over and over, forever.

    while Continued

    Modern Programming Languages - Chapter 13


    The return statement

    The return Statement

    <return-statement> ::= return <expression>; | return;

    • Methods that return a value must execute a return statement of the first form

    • Methods that do not return a value (methods with return type void) may execute a return statement of the second form

    Modern Programming Languages - Chapter 13


    Outline2

    Outline

    • 13.2 Thinking about objects

    • 13.3 Simple expressions and statements

    • 13.4 Class definitions

    • 13.5 About references and pointers

    • 13.6 Getting started with a Java language system

    Modern Programming Languages - Chapter 13


    Class definitions

    Class Definitions

    • We have enough expressions and statements

    • Now we will use them to make a definition of a class

    • Example: Int, a simple class wrapper of int to demonstrate parameter passing

    • Example: ConsCell, a class for building linked lists of integers as ML’s int list type

    Modern Programming Languages - Chapter 13


    Parameter passing by value

    Parameter passing by Value

    • Java uses pass by value exclusively. Before going further, it is important to define the terms pass by value and pass by reference. The term pass by value means that when an argument is passed to a function, the function receives a copy of the original value. Therefore, if the function modifies the parameter, only the copy is changed and the original value remains unchanged. The term pass by reference means that when an argument is passed to a function, the function receives the memory address of the original value, not a copy of the value. Therefore, if the function modifies the parameter, the original value in the calling code is changed.

    • Some of the confusion about parameter passing in Java programming originates from the fact that many programmers came to Java programming from C++. The C++ language contains both non-reference types and reference types and passes them by value and by reference, respectively. The Java programming language has primitive types and object references; and, therefore, it is logical to think that Java programming uses pass by value for the primitive types and pass by reference for references, much like C++. After all, you might think if you are passing a reference, it must be pass by reference. It is tempting to believe this, but it is not true.

    Modern Programming Languages - Chapter 13


    Parameter passing by value1

    Parameter passing by Value

    • In both C++ and Java programming, when a parameter to a function is not a reference, you pass a copy of the value (pass by value). The difference is with references. In C++, when a parameter to a function is a reference, you pass the reference or the memory address (pass by reference). In Java programming, when an object reference is a parameter to a method, you pass a copy of the reference (pass by value), not the reference itself. This is an important distinction. Note that Java programming does nothing differently when passing parameters of varying types like C++ does. Java programming passes all parameters by value, thus making copies of all parameters regardless of type.

    • Variables in Java programming can be one of two types: object types or primitive types. Both types are handled the same way when passed as arguments to a method. Both are passed by value; neither is passed by reference. The distinction is that formal parameters are not deferenced in a method. This is an important distinction as the subsequent code examples illustrate.

    Modern Programming Languages - Chapter 13


    Instance method invocation

    Instance method invocation

    • Java invokes methods by reference to an object instance as the first parameter.

    • Example: a.getInt( ) passes object referenced by a to the Int method getInt().

    • this implicit name of formal parameter of method object in an instance method.

    public class IntProg {    public static void main(String s[]) {        Int a = new Int(3);        System.out.println( a.getInt( ) );    }  }  class Int {    private int n;          public Int(int n) { this.n = n; }    public int getInt( ) { return this.n; }  }

    Modern Programming Languages - Chapter 13


    Java instance method side effects

    Java instance method side-effects

    public class IntProg {    public static void main(String s[]) {

       Int a = new Int(3);  a.assign(5);      System.out.println( a.getInt( ) );    }  }  class Int {    private int n;          public Int(int j) { this.n = n; }    public int getInt( ) { return this.n; } public void assign(int n) { this.n = n; }}

    • Only instance methods can access an object’s private attributes. Below a.assign(5) passes a objectreference to parameter this of the Int method assign() giving access to the private attribute n.

    Modern Programming Languages - Chapter 13


    Swap int

    Swap int

    public class SwapProg { 

    static void swap(int l, int r)

    {                  int t;                  t = l;                  l = r;                  r = t;

    public static void main(String s[]){

        int a = 3, b = 5;  swap(a, b);  System.out.println(a + " " + b); 

    } Output?

    Modern Programming Languages - Chapter 13


    Swap int objects

    Swap Int Objects

    public class SwapProg {     static void swap(Int l, Int r) {         Int t;         t = l;         l = r;         r = t;     }     public static void main(String s[]) {        Int a = new Int(3),        b = new Int(5);        swap(a, b);        System.out.println(a + " " + b);  }  }  Output?

    Modern Programming Languages - Chapter 13


    Assignment on objects

    Assignment on Objects

    • Swapping Int objects fails because parameters are passed by value

    • Only this can access the object directly by reference.

    • assign method assigns the parameter object i attribute value to this.n attribute.

    class Int { 

    private int n; 

    public Int(int n) { this.n = n; }  public void assign(Int i) { this.n = i.getInt( ); }public int getInt( ) { return this.n; }

    }

    Int a = new Int(3),

    b = new Int(5);

    a.assign(b); 

    • Questions:

    • Diagram a.assign(b);

    • Is getInt() needed? Why?

    200

    n

    3

    100

    200

    a

    201

    n

    5

    101

    201

    b

    Modern Programming Languages - Chapter 13


    Swap int objects1

    Swap Int Objects

    public class SwapProg {public static void main(String s[]) {      Int a = new Int(3),  b = new Int(5);      swap(a, b);      System.out.println(a + " " + b);  }  static void swap(Int l, Int r) {      Int t = new Int( );       t.assign(l);       l.assign(r);       r.assign(t);  }

    } Output?

    Modern Programming Languages - Chapter 13


    Exercise 1

    Exercise 1

    class Int {  private int n;    public Int(int n) { this.n = n; }  public void assign(Int i) { this.n = i.getInt( ); }public void assign(int i) { this.n = i; }public int getInt( ) { return this.n; }

    }

    • What is the following effect?Int a=new Int(3), b=a;

    • Diagram Question 1 showing references.

    • Followed by:b.assign(5);b = null;

    Modern Programming Languages - Chapter 13


    Using conscell

    Using ConsCell

    val a = [];ConsCell a = null;val b = 2::a;ConsCell b = new ConsCell(2,a);val c = 1::b;ConsCell c = new ConsCell(1,b);

    • :: does not create side-effects, difficult in ML

    • Java instance methods designed for side-effects

    • But a Java list should be object-oriented: where ML applies :: to a list, our Java list should be able to cons onto itself

    • And where ML applies length to a list, Java lists should compute their own length

    • Can’t use null for the empty list, not an object

    Modern Programming Languages - Chapter 13


    Conscell diagram

    ConsCell Diagram

    public ConsCell(int h, ConsCell t){ head = h; tail = t;}

    100

    100

    null

    1. ConsCell a = null;

    a

    2. ConsCell b = new ConsCell(2,a);

    null

    100

    a

    200

    b

    200

    100

    3. ConsCell c = new ConsCell(1,b);

    null

    100

    a

    300

    c

    300

    200

    100

    b

    200


    Conscell aliasing

    ConsCell Aliasing

    100

    100

    null

    1. ConsCell a = null;

    a

    2. ConsCell b = new ConsCell(2,a);

    null

    100

    a

    200

    b

    200

    100

    3. ConsCell c = new ConsCell(1,b);

    null

    300

    c

    300

    200

    100

    4. a = c;

    a

    300

    b

    200

    public ConsCell(int h, ConsCell t){ head = h; tail = t;}

    Aliasing - 300 is now referenced by a and c.


    Exercise 2

    public class ConsCell { private int head; private ConsCell tail; public void setHead(int head){ this.head = head; }

    Exercise 2

    • Diagram the effect of: ConsCell d = b;

    • Diagram the effect of: d.setHead(5);

    • Diagram the effect of: ConsCell e = new ConsCell(1,b);

    null

    100

    a

    300

    c

    300

    200

    100

    b

    200

    Modern Programming Languages - Chapter 13


    Conscell uncommented

    ConsCell uncommented

    public class ConsCell { private int head; // the first item in the list private ConsCell tail; // rest of the list, or null public ConsCell(int h, ConsCell t) { head = h; tail = t; } public int getHead() { return head; } public void setHead(int head) { this.head = head; }

    public ConsCell getTail() { return tail; }}

    Modern Programming Languages - Chapter 13


    Conscell commented

    ConsCell Commented

    /** * A ConsCell is an element in a linked list of ints. */public class ConsCell { private int head; // the first item in the list private ConsCell tail; // rest of the list, or null/** * Construct a new ConsCell given its head and tail. * @param h the int contents of this cell * @param t the next ConsCell in the list, or null */ public ConsCell(int h, ConsCell t) { head = h; tail = t; }

    Note comment forms, public and private, field definitions. Note constructor definition: access specifier, class name, parameter list, compound statement

    Modern Programming Languages - Chapter 13


    Conscell commented continued

    /** * @return the int contents of this cell */ public int getHead() { return head; }/** * @Side-effects this ConsCell head to parameter */ public void setHead(int head) { this.head = head; }

    /** * @return the next ConsCell in the list, or null */ public ConsCell getTail() { return tail; }}

    ConsCell Commented Continued

    Note method definitions: access specifier, return type, method name, parameter list, compound statement

    Modern Programming Languages - Chapter 13


    Using intlist

    Using IntList

    ML:Java:val a = nil; IntList a = new IntList(null);

    val b = 2::a; IntList b = a.cons(2);val c = 1::b; IntList c = b.cons(1);

    val x = length(a) + length(b) + length(c);

    int x = a.length() + b.length() + c.length();

    Modern Programming Languages - Chapter 13


    Using intlist continued

    Using IntList Continued

    public class IntList {private ConsCell start;public IntList(ConsCell s) { start = s; }public IntList cons (int h) { return new IntList(new ConsCell(h,start));}

    public class ConsCell { private int head; private ConsCell tail; public ConsCell(int h, ConsCell t) { head = h; tail = t; }

    IntList a = new IntList(null);

    IntList b = a.cons(2);

    IntList c = b.cons(1);

    a

    11

    11

    start

    10

    10

    null

    b

    21

    a

    11

    21

    11

    20

    start

    20

    start

    10

    head

    tail

    10

    2

    10

    null

    c

    31

    b

    21

    a

    11

    31

    21

    11

    start

    30

    start

    20

    30

    20

    start

    10

    head

    tail

    head

    tail

    10

    1

    20

    2

    10

    null


    Definition of intlist class and constructor

    Definition of IntList Class and Constructor

    /** * An IntList is a list of ints. */public class IntList { private ConsCell start; // list head, or null/** * Construct a new IntList given its first ConsCell. * @param s the first ConsCell in the list, or null */ public IntList(ConsCell s) { start = s; }

    An IntList contains a reference to a list of ConsCell objects, which will be null if the list is empty

    Modern Programming Languages - Chapter 13


    Definition of intlist cons method

    Definition of IntList cons method

    /** * Cons the given element h onto us and return the * resulting IntList. * @param h the head int for the new list * @return the IntList with head h, and us as tail */ public IntList cons (int h) { return new IntList(new ConsCell(h,start)); }

    An IntList knows how to cons things onto itself. It does not change, but it returns a new IntList with the new element at the front.

    Modern Programming Languages - Chapter 13


    Definition of intlist length method

    Definition of IntList length method

    /** * Get our length. * @return our int length */ public int length() { int len = 0; ConsCell cell = start; while (cell != null) { // while not at end of list len++; cell = cell.getTail(); } return len; }}

    An IntList knows how to compute its length

    Modern Programming Languages - Chapter 13


    Exercise 3

    Exercise 3

    public class IntList {private ConsCell start;public IntList(ConsCell s) { start = s; }public IntList cons (int h) { return new IntList(new ConsCell(h,start));}

    public class ConsCell { private int head; private ConsCell tail; public ConsCell(int h, ConsCell t) { head = h; tail = t; }

    • Add to the diagram the effects of:

      IntList d = b.cons(3);

    • Is a aliased by d?

    • Is c aliased by d?

    • Is d aliased by b?

    IntList c = b.cons(1);

    c

    31

    b

    21

    a

    11

    31

    21

    11

    start

    30

    start

    20

    30

    20

    start

    10

    head

    tail

    head

    tail

    10

    1

    20

    2

    10

    null


    Outline3

    Outline

    • 13.2 Thinking about objects

    • 13.3 Simple expressions and statements

    • 13.4 Class definitions

    • 13.5 About references and pointers

    • 13.6 Getting started with a Java language system

    Modern Programming Languages - Chapter 13


    What is a reference

    What Is A Reference?

    • A reference is a value that uniquely identifies a particular object (e.g. memory address).

    • What is passed to the IntList constructor is not an object—it is a reference to an object

    • What gets stored in start is not a copy of an object—it is a reference to an object, and no copy of the object is made

    public IntList(ConsCell s) { start = s; }

    Modern Programming Languages - Chapter 13


    Pointers

    Pointers

    • If you have been using a language like C or C++, there is an easy way to think about references: a reference is a pointer

    • That is, a reference is the address of the object in memory

    • Java language systems can implement references this way

    Modern Programming Languages - Chapter 13


    But i thought

    But I Thought…

    • Is Java C++ without pointers?

    • True from a certain point of view

    • C and C++ expose the address nature of pointers (e.g. in pointer arithmetic)

    • Programmer manipulates addresses directly, dangerous

    • Java programs can’t tell how references are implemented: they are just values that uniquely identify a particular object

    Modern Programming Languages - Chapter 13


    C comparison

    C++ Comparison

    • A C++ variable can hold an object or a pointer to an object. There are two selectors:

      • a->x selects method or field x when a is a pointer to an object

      • a.x selects x when a is an object

    • A Java variable cannot hold an object, only a reference to an object. Only one selector:

      • a.x selects x when a is a reference to an object

    Modern Programming Languages - Chapter 13


    C java reference comparison

    C++

    Equivalent Java

    IntList* p;p = new IntList(0);p->length();p = q;

    IntList p;p = new IntList(null);p.length();p = q;

    IntList p(0); // Implicitp.length();p = q;

    No equivalent.

    Must invoke IntList constructor explicitly using new.

    C++/Java Reference Comparison

    Modern Programming Languages - Chapter 13


    Java reference side effect example

    Java Reference Side-effect Example

    • Object variables hold references to an object

    • When two or more variables reference the same object, the object is aliased

    • The following example illustrates how natural side-effects are in imperative languages

    • And the dangerous assignment operation

    • ML and functional languages in general discourage the use of assignment

    Modern Programming Languages - Chapter 13


    Side effect example

    Side-effect Example

    public class Point {

    private int x, y;

    private Color myColor = Color.blue;

    public void move(int newX, int newY) {

    x = newX;

    y = newY;

    }

    }

    public class PointUse {public static void main( String arg[])

    {

    Point a = new Point();

    a.move( 100, 250);

    b = a;

    b.move( 0, 0);

    }

    • What are x and y of Point a at the end?

    Modern Programming Languages - Chapter 13


    Outline4

    Outline

    • 13.2 Thinking about objects

    • 13.3 Simple expressions and statements

    • 13.4 Class definitions

    • 13.5 About references and pointers

    • 13.6 Getting started with a Java language system

    Modern Programming Languages - Chapter 13


    Text output

    Text Output

    • A predefined object: System.out

    • Two methods: print(x) to print x, and println(x) to print x and start a new line

    • Overloaded for all parameter types

    System.out.println("Hello there");System.out.print(1.2);

    Modern Programming Languages - Chapter 13


    Printing an intlist

    Printing An IntList

    /** * Print IntList object to System.out. */ public void print() { System.out.print("["); ConsCell a = start; while (a != null) { System.out.print(a.getHead()); a = a.getTail(); if (a != null) System.out.print(","); } System.out.println("]"); }

    Added to the IntList class definition, this method gives an IntList the ability to print itself out

    Modern Programming Languages - Chapter 13


    The main method

    The main Method

    • A class can have a main method like this:

    • This will be used as the starting point when the class is run as an application

    • Keyword static makes this a class method; use sparingly!

    public static void main(String[] args) { …}

    Modern Programming Languages - Chapter 13


    A driver class

    A Driver Class

    class Driver { public static void main(String[] args) { IntList a = new IntList(null); IntList b = a.cons(2); IntList c = b.cons(1); int x = a.length() + b.length() + c.length(); a.print(); b.print(); c.print(); System.out.println(x); }}

    Modern Programming Languages - Chapter 13


    Compiling the program

    Compiling The Program

    • Three classes to compile, in three files:

      • ConsCell.java, IntList.java, and Driver.java

    • (File name = class name plus .java—watch capitalization!)

    • Compile with the command javac

      • They can be done one at a time

      • javac Driver.java compiles all since Driver.java uses IntList which uses ConsCell.

    Modern Programming Languages - Chapter 13


    Running the program

    Running The Program

    • Compiler produces .class files

    • Use the Java launcher (java command) to run the main method in a .class file

    C:\demo>java Driver[][2][1,2]3

    Modern Programming Languages - Chapter 13


    Java at ius

    Java at IUS

    To compile and execute Driver.java, enter following commands at the Command Prompt:

    v:\common\user\c311\forJavajavac -cp . Driver.javajava Driver

    Modern Programming Languages - Chapter 13


    Java at home

    Java at Home

    • Java is freely available from the SUN Java website.

    • Download the software and follow the instructions for installing the Java SDK.

    • To compile and execute Driver.java, enter following commands at the Command Prompt:

      javac -cp . Driver.javajava Driver

    Modern Programming Languages - Chapter 13


    Exercise 4

    Exercise 4

    • Open a Command prompt window.

    • Enter:notepad HelloWorld.java

    • Copy, paste, save to your H: drive the following program into Notepad.

    • At H> prompt enter:v:\common\user\c311\forJavajavac -cp . Hello.javajava Hello

    public class Hello {public static void main( String args[ ] ) {System.out.println("Hello World"); }}

    Modern Programming Languages - Chapter 13


  • Login