algorithm programming 1 89-210 bar-ilan university 2007-2008 תשס"ח by moshe fresko

27
Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 חחח"חby Moshe Fresko

Upload: deirdre-wade

Post on 04-Jan-2016

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Algorithm Programming 189-210

Bar-Ilan University

תשס"ח 2007-2008

by Moshe Fresko

Page 2: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Java Language Specifications

Page 3: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Controlling Program Flow Operators

Addition(+), subtraction and unary minus(-), multiplication(*), division(/), assignment(=) etc.

Produces a Value Side Effect Operators work only with primitives, except

=,==,!= for objects and +,+= for String Operator Precedence Assignment =

Page 4: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Primitive Data TypesType Size Min Max Wrapper Defautboolean - - - Boolean falsechar 16-bit Uni 0 Uni 216-1 Character ‘\u0000’byte 8-bit -128 +127 Byte (byte)0short 16-bit -215 +215-1 Short (short)0int 32-bit -231 +231-1 Integer 0long 64-bit -263 +263-1 Long 0Lfloat 32-bit Float 0.0fdouble 64-bit Double 0.0dvoid - Void

Page 5: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Assignment Operator (=) lvalue=rvalue rvalue is constant, variable, or expression lvalue is a physical space to store the value Primitive assignment Object assignment

class Number { int i; }public class Assignment { public static void main(String[] args) { Number n1 = new Number(); Number n2 = new Number(); n1.i = 9; n2.i = 47; System.out.println("1: n1.i: " + n1.i + ", n2.i: " + n2.i); n1 = n2; System.out.println("2: n1.i: " + n1.i + ", n2.i: " + n2.i); n1.i = 27; System.out.println("3: n1.i: " + n1.i + ", n2.i: " + n2.i); }}

Page 6: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Function Calls Aliasing can occur in Function Callclass Letter { char c; }public class PassObject { static void f(Letter y) { y.c = 'z'; } public static void main(String[] args) { Letter x = new Letter(); x.c = 'a'; System.out.println("1: x.c: " + x.c); f(x); System.out.println("2: x.c: " + x.c); }}

Primitive types pass as copy by value Values are returned as return-by-value

Page 7: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Mathematical Operatorsint i, j, k; float f, g, h;... ...i = j + k; f = g + h;i = j - k; f = g - h;i = k / j; f = g / h;i = k * j; f = g * h;i = k % j; i += j; f += g;i -= j; f -= g;i /= j; f /= g;i *= j; f *= g;i %= j;i = -j; f = -g;i = +j; f = +g;i++; ++i;i--; --i;

Page 8: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Relational Operators Have only boolean result Works on built-in data types <, >, <=, >=, ==, != == and != also work with objects (reference check)

public class Equivalence { public static void main(String[] args) { Integer n1 = new Integer(15); Integer n2 = new Integer(15); System.out.println(n1 == n2); System.out.println(n1 != n2); }}

equals ( ) : for comparing object contents

Moshe
But default behaviour of equals() is reference comparison. So on any newly declared class it must be overridden.
Page 9: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Logical Operators AND (&&), OR (||) and NOT (!) Short circuited

public class ShortCircuit { static boolean test1(int val) { System.out.println("test1(" + val + ")"); return val < 1; } static boolean test2(int val) { System.out.println("test2(" + val + ")"); return val < 2; } static boolean test3(int val) { System.out.println("test3(" + val + ")"); return val < 3; } public static void main(String[] args) { if(test1(0) && test2(2) && test3(2)) System.out.println("expression is true"); else System.out.println("expression is false"); }}

Page 10: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Bitwise and Shift Operators Bitwise operators

AND operator (&) OR operator (|) XOR operator (^) Bitwise NOT operator (~) is unary operator &=, |=, ^=

Shift operators << Left Shift >> Right Shift >>> Unsigned Right Shift with Zero Extension char, byte, or short will be promoted to int. int will use 5 low-order bits of rhs long will use 6 low-order bits of rhs <<=, >>=, >>>=

Page 11: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Operators Ternary if-else operator

boolean-exp ? value0 : value1 static int ternary(int i) { return i < 10 ? i * 100 : i * 10; }

The comma operatorOnly in for loops

String operator +int x = 0, y = 1, z = 2; String sString = "x, y, z ";System.out.println(sString + x + y + z); System.out.println(x + sString);

Page 12: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Operators Common pitfalls

while(x = y) { ... } instead of x==yCompiler error unless x and y are booleanif (x&y) { … } instead of x&&yCompiler catches this error

Castingint i = 200; long l = (long)i;

// superfluous cast, is not necessary, but clearer codechar c = (char) i ;

// necessary, otherwise does not compile Object casts

class B extends A { }a = b ; // okb = a ; // compiler error : incompatible typesb = (B) a ; // compiler ok, but run-time check (can throw ClassCastException)

Page 13: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Literalschar c = 0xffff; // max char hex value byte b = 0x7f; // max byte hex value short s = 0x7fff; // max short hex value int i1 = 0x2f; // Hexadecimal (lowercase) int i2 = 0X2F; // Hexadecimal (uppercase) int i3 = 0177; // Octal (leading zero) // Hex and Oct also work with long. long n1 = 200L; // long suffix long n2 = 200l; // long suffix (but can be confusing) long n3 = 200; float f1 = 1; float f2 = 1F; // float suffix float f3 = 1f; // float suffix float f4 = 1e-45f; // 10 to the power float f5 = 1e+9f; // float suffix double d1 = 1d; // double suffix double d2 = 1D; // double suffix double d3 = 47e47d; // 10 to the power

Page 14: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Precedence Unary +, -, ++, -- Arithmetic & Shift +, -, *, /, %, <<, >>,

>>> Relational <, >, ==, >=, <=, != Logical & Bitwise &&, ||, &, |, ^ Conditional A > B ? X : Y Assignment =, *=, +=, etc.

Page 15: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Execution Control if (Boolean-expression)

statement if (Boolean-expression)

statement else

statement while (Boolean-expression)

statement do

statement while(Boolean-expression);

for(initialization; Boolean-expression; step) statement

Page 16: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Execution Control return, continue, break, continue label, break label

label1: outer-iteration {

inner-iteration { //... break; //... continue; //... continue label1; //... break label1;

} }

switch, case, breakswitch(integral-selector) {

case integral-value1 : statement; break; case integral-value2 : statement; break; …default: statement;

}

Page 17: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Constructor Default Constructor

class Rock { Rock() { System.out.println("Creating Rock"); }

} public class SimpleConstructor {

public static void main(String[] args) {for(int i = 0; i < 10; i++)

new Rock(); }

}

Constructors with Parametersclass Rock {

Rock(int i) { System.out.println("Creating Rock"+i); } } public class SimpleConstructor {

public static void main(String[] args) {for(int i = 0; i < 10; i++)

new Rock(i); }

}

Page 18: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Method Overloadingclass Tree {

int height; Tree() {

System.out.println("Planting a seedling"); height = 0;

} Tree(int i) {

System.out.println("Creating new Tree " + i + " feet tall"); height = i;

} void info() {

System.out.println("Tree is " + height + " feet tall"); } void info(String s) {

System.out.println(s + ": Tree is " + height + " feet tall"); }

}

Page 19: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Method Overloading Java distinguishes between overloaded methods according to

parameters.void p(string s, int i) { … }void p(int i, string s) { … }

Overloading with primitivesvoid p(byte b) { … }void p(int i) { … }… p(100) ; // p(int) is called

No overloading on return values Default constructor

class Bird { int i; }… new Bird() ; // ok class Hat { int i ; Hat(int x) { i=x; } }… new Hat() ; // compiler error

Page 20: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

this this keyword

this.func() return this

Calling constructors from constructorsclass Flower {

Flower(int i) { … }Flower(string s) { … }Flower(int i,string s) {

this(i) ; // The first line, and only once…

}}

this cannot be used in Static methods

Page 21: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Clean up GC : Garbage Collection No destructor, only finalize() method neither GC nor finalize() is guaranteed System.gc( ) can be called for GC

Page 22: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Member Initialization Primitive Data types are initialized automatically Object Reference is initialized to null Specifying initialization (either in Class definition or in

Constructor)class X {

boolean b = true; char c = 'x'; Depth d = new Depth();int i = f(); int j = g(k) ; // Compiler Errorint k ; { k = 30 ; … }

Order of initialization, like the order of members in the class definition

Page 23: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Static Initialization Can be initialized in either way

static int i ; static int j = 3 ; static int k ;

static { k = 5 ; … } Static members are initialized when

A new object created Any static member is accessed

Page 24: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Array Initialization int a[] ; int[] a ; int[] a = { 1, 2, 3, 4, 5 }; int[] a = new int[5] ; X[] a = { new X(1), new X(2), new X(5) }

a.length

Page 25: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Multi-dimensional Arrays int[][] a ; int[][] a = { { 1, 2, 3, }, { 4, 5, 6, } }; int[][][] a = new int[2][2][4]; int[][][] a = new int[3][][];

a[2] = new int[5][]; a[2][3] = new int[6];

X[][] x = { { new X(1), new X(2) } , { new X(3) } } X[][] x = new X[3][] ;

x[1] = new X[4] ;x[1][2] = new X(54) ;

Page 26: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Array Parameters and Return Values void f(int[] array) { … }

int[] n = new int[100] ;obj.f(n) ;

Arrays are passed as object reference int[] initNewArray(final int sz, final int val)

{ int[] arr = new int[sz] ; … ; return arr ; }int[] a = initNewArray(10,4) ;

java.util.Arrays. binary_search(…,…) equals(…,…) fill(…,…,…,…) sort(...)

Page 27: Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko

Arrays Index from 0 Arrays are created with new Arrays are treated as regular objects Boundary errors are found at runtime Don’t use regular arrays for dynamic arrays, it

can waste memory and time, and can create non-readable code