Вы находитесь на странице: 1из 25

Motivation for Strong Typing

Type declarations provide extra information associated with an identifier. This redundant info. enables mechanical detection of errors. In practice, a number of logical and typographical errors manifest themselves as type errors. Thus, strongly typed languages allow construction of reliable programs. In OOPLs, the type tags associated with objects aid in the impl. of dynamic binding, polymorphism, and safe conversions.
CS480(Prasad) L5Types 1

Typing
variable reference (text) (pointer) Static Typing (e.g., Ada)
type(variable) = type(object) compile-time checking : efficient

object (memory)

Dynamic Typing (e.g., Scheme)


variables type-less; objects carry type tags run-time type-checking : flexible
CS480(Prasad) L5Types 2

Typing in OOPL (E.g., Java, Eiffel, C++, )


type(object/reference) is-a-subtype-of type (variable). In Java, a variable of class C, can hold a reference to an instance (object) of a subclass of C.

Type correctness guaranteed at compile-time.


Efficient and secure.

Dynamic binding dispatches each call to the appropriate code, at run-time.


Flexible handling of heterogeneous data.

CS480(Prasad)

L5Types

Arrays

CS480(Prasad)

L5Types

Arrays
Declaration
int[] intArray; String[] args;

Creation
intArray = new int[5]; intArray = { 0, 2, 4, 3*2, 4+4 };

Array of arrays (cf. multi-dimensional array)


double [][] iA = { { 1, 0 }, null };

Java runtime verifies that array indices are in the correct range.
CS480(Prasad) L5Types 5

An Example Program
class EchoArgs { public static void main(String[] args){ for (int i = 0; i < args.length; i++) System.out.print( args[i] ); }; System.out.println( ); } javac EchoArgs.java java EchoArgs a 23 c abc java EchoArgs
CS480(Prasad) L5Types 6

Java 5 version
class EchoArgs { public static void main(String[] args){ System.out.print("Command line arguments: "); for (String s : args) System.out.printf( " %s ", s ); System.out.println("."); } }

javac java

EchoArgs.java EchoArgs a 23 c ab

CS480(Prasad)

L5Types

4
args

a 23 c abc

(local variable on stack)

(array object on heap)

(string objects on heap)

CS480(Prasad)

L5Types

class PascalTriangle { public static void main( String[] args ) { n = Integer.parseInt( args[0] ); int [] [] pT = new int [n + 1] []; pT[0] = new int[1]; // first row pT[0][0] = 1; for (int i = 1; i <= n; i++) {// rows 2 to n+1 pT[i] = new int [i + 1]; pT[i][0] = 1; pT[i][i] = 1; for (int j = 1; j < i ; j++ ) { pT[i][j] = pT[i-1][j-1] + pT[i-1][j]; } } }

CS480(Prasad)

L5Types

3
pT

1
2

1 1
3

(int array objects on heap)

1 (local variable on stack) (array object on heap) 2 1

CS480(Prasad)

L5Types

10

C# Equivalent
using System; class PascalTriangleInCSharp { public static void Main( string[] args ) { int n = 7; if (args.Length > 0) n = int.Parse( args[0] ); int [] [] pT = new int [n + 1] []; pT[0] = new int[1]; pT[0][0] = 1; for (int i = 1; i <= n; i++) { pT[i] = new int [i + 1]; pT[i][0] = 1; pT[i][i] = 1; for (int j = 1; j < i ; j++ ) { pT[i][j] = pT[i-1][j-1] + pT[i-1][j]; } } }
CS480(Prasad) L5Types 11

C# Alternative
using System; class RectArrayInCSharp { public static void Main( string[] args ) { const int n = 7; int [,] pT = new int [n,n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { pT[i,j] = i + j; } } System.Console.WriteLine(pT); } }

CS480(Prasad)

L5Types

12

Array type : unconstrained


Define matrix operations in terms of structure of the array (dimensionality); size is implicit.
Vector dot-product that works for two equal length single-dimension array with same type elements. Matrix multiplication : Dimension compatibility checked at run-time. length field of an array object used :

to control loops. to allocate storage for local variables.


Type is unconstrained, but each object/instance has a fixed size. (E.g., String type vs String object ) Cf. Ada Unconstrained array types.
CS480(Prasad) L5Types 13

Java Generics

CS480(Prasad)

L5Types

14

import java.util.*; public class OldList { public static void main(String args[]) { List list = new ArrayList(); // (Potentially heterogeneous collection) list.add("one"); list.add("two"); list.add("three"); list.add("four"); Iterator itr = list.iterator(); while(itr.hasNext()) { // Explicit type cast needed String str = (String) itr.next(); System.out.println(str + " is " + str.length() + " chars long."); } } }
CS480(Prasad) L5Types 15

import java.util.*; public class NewList { public static void main(String[] args) { List <String> list = new LinkedList <String>(); // Instantiating generic type. // (Homogeneous collection) list.add("one"); list.add("two"); list.add("three"); list.add("four"); for (String str : list) { System.out.printf("%s is %d chars long.\n", str, str.length()); }; } }
CS480(Prasad) L5Types 16

using System; using System.Collections.Generic; public class NewList { public static void Main(string [] args) { // List class supports method Add LinkedList <String> list = new LinkedList <String>(); // Instantiating generic type. // (Homogeneous collection) list.AddFirst("one"); list.AddLast("two"); list.AddLast("three"); list.AddLast("four"); foreach (string str in list) { System.Console.WriteLine(str + " is " + str.Length + " chars long."); }; } }
CS480(Prasad) L5Types 17

Character Strings
class String class StringBuffer (Java 1.4 and before : thread-safe) class StringBuilder (Java 5 : thread-unsafe)

(Cf. array of characters)


Based on 2-byte Unicode characters

cs480 (Prasad)

L9Strings

18

class String vs class StringBuffer/StringBuilder immutable


contents of String instance unchangeable cannot insert or append characters

mutable
contents of
StringBuffer

instance

modifiable

growable
grows automatically when characters added sb.length() sb.capacity() total allocated capacity
19

fixed length
s.length() number of characters in the string
cs480 (Prasad)

L9Strings

String literals and concatenation


String s = abc ; System.out.println( s + def );

+ stands for string concatenation. Built-in operator overload.

Left associativity of
(s + (s + 3 + 5) (3 + 5))

+
abc35 . abc8 . 8abc .

evaluates to evaluates to evaluates to


L9Strings

(5 + 3 + s)

cs480 (Prasad)

20

String conversions
supports toString()-method to convert a class instance into a printable string form: classname@hashcode toString() can be overridden.
class Object public String toString() { ... }; println/print

methods in System.out, the + -expressions, and the += -statements invoke toString() implicitly, to coerce an instance to a string.
L9Strings 21

cs480 (Prasad)

Assignment
String s = abc ; s += 2+3+5; s.equals( abc10 ) == true s.equals( abc235 ) == false (Recall that + is left-associative.)

Type E1; E1 += E2; E1 = (Type) ((E1) + (E2))


cs480 (Prasad) L9Strings 22

TYPE
boolean

TO

STRING

FROM

STRING

String.valueOf(boolean)

new Boolean(String). booleanValue()

int long float

String.valueOf(int)

Integer.parseInt(String)

String.valueOf(long)

Long.parseInt(String) new Float(String). floatValue()

String.valueOf(float)

double

String.valueOf(double)

new Double(String). doubleValue()

cs480 (Prasad)

L9Strings

23

Comparison
abc .equals( abc )

is

true.

abc .equalsIgnoreCase( ABC ) abc == new String( abc )

is is

true. false.

s == s

is

true.

s1.compareTo(s2) negative: s1 lexicographically precedes s2 zero: s1 is equal s2 positive: s1 lexicographically follows s2


cs480 (Prasad) L9Strings 24

Useful Methods
String t = abca ; String s = new String(t); s.charAt(2) s.indexOf( a ) s.indexOf( bc ) s.indexOf( a ,2) s.lastIndexOf( a )

is is is is is

c . 0. 1. 3. 3.

regionMatches, startsWith, endsWith, etc.

Pure ASCII applications can be inefficient because Java uses 16-bit Unicode characters.
cs480 (Prasad) L9Strings 25

Вам также может понравиться