<<

Fundamental Constructs

Chapter 3

Copyright © 1998-2003 Delroy A. Brinkerhoff. All Rights Reserved. Chapter 3 Slide 1 of 24

Intrinsic Types Simple, built-in data types

type range values comments

void 0 return type boolean 1? true, false 1 -27 to 27-1 -128 to 127 char 2 0 to 216-1 0 to 65535 unicode short 2 -215 to 215-1 -32768 to 32767 int 4 -231 to 231-1 -2147483648 to 2147483647 long 8 -263 to 263-1 ~ -9.223×1018 to ~9.223×1018 float 4 ~ -3.40×1038 to ~3.40×1038 6 sig digs double 8 ~ -1.798×10308 to ~1.798×10308 15 sig digs PSize and byte-order are Java-defined Pint is the smallest supporting arithmetic < Arithmetic on char is not allowed PSigned -2bits-1 to 2bits-1 - 1; Unsigned 0 to 2bits - 1 Chapter 3 Slide 2 of 24 Type Promotions and Casts Type promotions (see illustration, p. 48)

PRules of automatic type promotions < Automatic when going from “narrow” to “wide” data types – Wider means a greater range, not number of bytes – The wide type must encompass the full range of the narrow type – Expression type is type of widest operand –byte ö short ö int ö long (8 bytes) ö float (4 bytes) ö double < int is the smallest data type supporting arithmetic < Ordinal constants are int and floating point constants are double PExplicit cast required to convert from “wide” to “narrow” type < int i = (int) 3.14; < int i = (int) (3.14 + 2.7); < double d = (double) 1 / 3; PBoolean values are not castable (period! see C++ note p. 49) PCan’t cast to or from String (must use methods; see p. 56) Chapter 3 Slide 3 of 24

Java™ “Library” Features Symbolic or named constants and methods (functions)

public final class Math PEverything is in a class { PUsually in lang or util private Math( ) { } P“static” makes one copy public static final double PI = 3.14159;

P“final” prevents change public static final double sin(double x) PSymbolic constants { ... < C/C++ } – #define } – enum < Java – public static final x = 2 * Math.PI; – Names are upper case y = Math.sin(x/y);

Chapter 3 Slide 4 of 24 Wrapper Classes Object versions of intrisic data types in the java.lang package

PJava™ predefines classes for some of the simple data types < Integer < Float < Character < Long < Double < Boolean PMethods < int Integer.parseInt(String number) – int i = Integer.parseInt("123"); < double Double.parseDouble(String number) – double x = Double.parseDouble("3.14159"); < boolean equals(Object o) – Integer count = new Integer("123"); Integer max = new Integer("1000"); count.equals(max) < String toString() – String x = Integer.toString(i); – Stringx=i+""; Chapter 3 Slide 5 of 24

String Class java.lang.String PInstantiation < String greeting = “Hello world”; // preferred < String greeting = new String(”Hello world”); // not preferred PMethods < greeting.compareTo(”hello world”); // like strcmp < greeting.equals(”hello world”); // boolean < greeting.equalsIgnoreCase(”hello world”); // boolean < greeting.length(); // 11 < greeting.substring(1,5); // “ello” < greeting.indexOf(’o’); // 4 < greeting.indexOf(”world”); // 6 < greeting.concat(” from Java™”) < greeting + “ from Java” // String concatenation < greeting += “ from Java” // String concatenation and assignment Chapter 3 Slide 6 of 24 StringBuffer Class java.lang.StringBuffer

PAnalogous to C++’s strstream classes PConstructors < StringBuffer SB = new StringBuffer( ); < StringBuffer SB = new StringBuffer(11); < StringBuffer SB = new StringBuffer(”Hello world”); PDynamically sized (but changing size may be expensive) PMethods (some) < SB.append(” from Java”); // may also be numeric or char < SB.capacity( ); < SB.length( ); < SB.setLength(15); < SB.insert(11, ‘*’); < SB.insert(11, “********”); Chapter 3 Slide 7 of 24

StringTokenizer Class java.util.StringTokenizer vs strtok

PStringTokenizer(String s [,String delim [,boolean rd ] ]) < Parameters – s string to tokenize (not changed) – delim string of delimiter characters (separates tokens, white space by default) – rd return delimiter (nextToken returns delimiter ) < boolean hasMoreTokens( ) < String nextToken([String delim])

String S = "See the quick\tred fox\njump over the lazy brown dog";

StringTokenizer T = new StringTokenizer(S, " \t\n");

while (T.hasMoreTokens( )) System.out.println(T.nextToken( ));

Chapter 3 Slide 8 of 24 Formating Numbers java.text.NumberFormat PNumberFormat f; < f = NumberFormat.getInstance(); < f = NumberFormat.getCurrencyInstance(); < f = NumberFormat.getNumberInstance(); < f = NumberFormat.getPercentInstance(); PMethods < String f.format(number); < setMinimumIntegerDigits / setMaximumIntegerDigits < setMinimumFractionDigits / setMaximumFractionDigits < Locale[ ] locales = NumberFormat.getAvailableLocales( ); Pjava.util.Locale < Constants: Locale.CANADA, Locale.JAPAN, Locale.US, etc. < static void setDefault(Locale newLocale) < static Locale getDefault( ) Chapter 3 Slide 9 of 24

Objects Created (instantiated) from classes PObjects are instances of classes < All objects are instantiated dynamically on the heap with new (3 exceptions: String constants, statically initialized arrays, and object factories-- static methods that create and return objects) < Attributes of each object are separate and distinct < Objects are named with reference variables allocated on the stack < Anonymous objects are not named (i.e., not assigned to a reference) < instanceof operator left hand operand is an object, right hand operand is a class; boolean valued < Examples – Circle C; // define reference var – C = new Circle(10,0,0); // instantiation only – Circle C = new Circle(10,0,0); // both in 1 statement – new Circle(10,0,0); // anonymous object c null c 101 object

Chapter 3 Slide 10 of 24 Java™ Collects Garbage No explicit object deallocation (i.e., no delete operator)

PJava™ provides automatic garbage collection (there is no delete operator) < Java™ uses a mark-and-sweep algorithm – Implemented as a low-priority thread – Suspends execution of user program – Mark all allocated heap memory as unused – Follow pointers and mark reached memory as used – Reclaim unmarked memory < “C++ programmers know that memory management is too important to leave up to the system; Smalltalk [Java] programmers know that memory management is too important to leave up to programmers” – Bjarne Strustrup PNote that garbage collection cannot be forced (System.gc() and Runtime.gc() not withstanding)

Chapter 13 SlideSlide 11 7 of 2420

Arrays Always are instantiated objects (see p. 96)

PVariable definition is distinct from object instantiation < int monLength[ ]; // variable definition < monLength = new int[12]; // object instantiation < int monLength[ ] = new int[12]; // both PStatic instantiation and initialization < int monLength[ ] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; PIndexed 0 .. size - 1 < Index is bounds checked (errors throw an exception) PmonLength.length; // capacity, not filled slots PArray declaration syntax < int[] monLength; or int monLength[]; < The first is useful for method return types: int[] func(void)

Chapter 3 Slide 12 of 24 Arrays of Objects Arrays of objects are really arrays of pointers to objects

Employee emp[ ];

emp = new Employee[5];

for (int i = 0; i < emp.length; i++) emp[i] = new Employee( );

Chapter 3 Slide 13 of 24

AND and OR Operators Logical and bitwise

PLogical operators (left and right hand operands are boolean)

< && short-circuit E1 && E2 if E1 is false, E2 not evaluated < & non-short-circuit E1 & E2 E2 is always evaluated < || short-circuit E1 || E2 if E1 is true, E2 not evaluated < | non-short-circuit E1 | E2 E2 always evaluated PBitwise operators (left and right hand operands are numeric)

a b a & b a b a | b a b a ^ b a ~a

0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 1 0 1 1 0 1 1 0 0 1 0 1 1 0 1 1 1 1 1 1 1 1 1 0

Chapter 3 Slide 14 of 24 -Shifting Operations bitwise operations

PBit-shifting < right hand operand is mod the number of of left hand operand P<< 11001100 << 2 º 00110000 < each bit shifted is equivalent to × 2 P>> 11001100 >> 2 º 11110011 < 01001100 >> 2 º 00010011 < preserves sign; each bit shifted is equivalent to ÷ 2 P>>> 11001100 >>> 2 º 00110011 < always pads on the left with 0; each bit shifted is equivalent to ÷ 2 PExamples < 10 << 34 º 40 10 << (34 % 32) = 10 << 2 = 10 × 2 × 2 = 40 < -20 >> 2 º -5 -20 >> 2 = -20 ÷ 4 = trunc(-5) = -5 < -21 >> 2 º -6 -21 >> 2 = -21 ÷ 4 = trunc(-5.25) = -6 Chapter 3 Slide 15 of 24

Simple Program Structure Method order within class is not fixed public class Demo { private double value;

public Demo(String input) { value = Double.parseDouble(input); }

public double sqr( ) { return value * value; }

public static void main(String[ ] args) { Demo d = new Demo(args[0]); double y = d.sqr( ); } } // class Square Chapter 3 Slide 16 of 24 Sending Messages Objects communicate/cooperate/collaborate by exchanging messages PEvery message has a sending object and a receiving object PA message is a high-level concept < Equivalent to an operation or behavior (i.e., what an object can do) < Implemented by one or more methods or functions sending object SalesDepartment sales = new SalesDepartment( ); receiving object message salesManager.calcPay( ); public class SalesDepartment public class Employee { private Employee salesManager; { private doublehours; private double pay; private doublerate;

public void f( ) public doublecalcPay( ) { { pay = salesManager.calcPay( ); . . . } } } } Chapter 3 Slide 17 of 24

Method Definition Syntax Summary / review PAlways defined inside a class but can not be nested PHeader < Modifiers (0 or more; common: public, private, etc.) < Return value type (required, may be void) < Name (Java style is “Camel notation”) < Argument list (the ‘(’ and ‘)’ are always required) < Method signature = Name + Agrument list < Definition requires typing info; documentation shown in this format PBody < Between ‘{’ and ‘}’ < Contains any number of legal Java statements (including 0) public class Employee { public Manager getBoss(int depart, Date when) { ...... } public static int getPhoneNumber( ) { ...... } } Chapter 3 Slide 18 of 24 Method Call Syntax Summary / review

PDoes not include modifiers or typing information PNon-static methods are called through an object PStatic methods are called through the class

Employee worker = new Employee( ); Manager boss = worker.getBoss(416, new Date( )); int number = Employee.getPhoneNumber( );

public class Bar { public Bar( ) { someMethod( ); // calling object is new Bar object being built } } Chapter 3 Slide 19 of 24

Objects and Methods Summary / review

PNon-static methods are always called through an object < The object is a default target for the method < The object is bound to the method through the “this” reference public class Foo Foo f1 = new Foo(10); { private int number; Foo f2 = new Foo(20); public Foo(int n) int count = f1.bar(f2); { number = n; }

public int bar(Foo f) { return number + f.number; } } Chapter 3 Slide 20 of 24 Object Assignment and Reference Creating object aliases

PObject names are references that “point” to an object PMultiple names (aliases) may reference the same object < Created by assignment < Created by method calls t 101 object name object type (class name)

Circle c = new Circle(100,20,10); Circle t = c; // doesn’t duplicate 101 draw(c); // method call c Circle Object

void draw(Circle s) { }

if (c == null) . . . s 101

Chapter 3 Slide 21 of 24

Pass By Value: Simple Types Illustrated with int

int x = 100; xxx x inc(x); 100 100 100 100 a a void inc(int a) { 100 200 a += 100; define x call inc run inc return }

time

Chapter 3 Slide 22 of 24 Pass By Value: Objects Assume class Employee

PJava™ only has xxx x pass by value 101 101 101 101 PThe value passed is an address Fred Fred Fred Fred

Employee x = 101 a 371 a new Employee(”Fred”);

update(x); Sid void update(Emp a) { define x call updaterun update return a = new Employee(”Sid”); } time Chapter 3 Slide 23 of 24

Pass By Value: Updating Objects Class Employee has an instance variable name

xxx x 101 101 101 101

Employee x = Fred Fred Sid Sid new Employee(”Fred”);

update(x); 101 101 a a void update(Emp a) { define x call updaterun update return a.name = ”Sid”; } time

Chapter 3 Slide 24 of 24