Download
a first look at java n.
Skip this Video
Loading SlideShow in 5 Seconds..
A First Look At Java PowerPoint Presentation
Download Presentation
A First Look At Java

A First Look At Java

172 Views Download Presentation
Download Presentation

A First Look At Java

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. A First Look At Java Download as Power Point file for saving or printing. Modern Programming Languages - Chapter 13

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

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

  4. 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() ); } }

  5. Object Oriented Example • Colored points on the screen • Data? • Coordinates • Color • Operations? • Move itself • Report its position Modern Programming Languages - Chapter 13

  6. 3 PointObjects Modern Programming Languages - Chapter 13

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

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

  9. Java Class Definitions: A Peek

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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