31
CS 884 (Prasad) Java Examples 1 Java Examples Java Language Constructs

CS 884 (Prasad)Java Examples1 Java Language Constructs

Embed Size (px)

Citation preview

Page 1: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 1

Java Examples

Java Language Constructs

Page 2: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 2

Java Program Organization

• Compilation Unit = File

• Package = Directory– A Java program is a set of compilation

units organized using a package hierarchy (that is, as a forest of trees).

– A compilation unit is a set of class and interface declarations.

– Every compilation unit belongs to a unique (possibly unnamed) Java package.

Page 3: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 3

• Every file (compilation unit) can have at most one public class.

• The definition of public class PC must be in a file named PC.java. – Set environment variables CLASSPATH and PATH appropriately.

• To compile: > javac PC.java

• To run: > java PC

• To run applets: > netscape PC.html

> appletviewer PC.html

Page 4: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 4

Class Declaration– Fields / Instance Variables (Holds state)

• x, y

– Constructors (Initializes state)• Point

– Methods (Proc/Func) (State Transformer/Observer)• move

– Class Variables (Global to all instances)• count

– Local Variables / Formal Parameters

Page 5: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 5

Interface Declaration

interface Table { boolean isEmpty(); void insert(Object x, int key); Object lookUp(int key);}

– An interface specifies constants and signatures of the methods.

– An interface can extend several super-interfaces.

Page 6: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 6

Class implements Interface

import java.util.Hashtable;

class Index implements Table {

HashTable v = new Hashtable();

public boolean isEmpty() {

return v.isEmpty(); }

public void insert(Object x, int key) {

v.put(new Integer (key) , x); }

public Object lookUp(int key) {

return v.get(new Integer ( key ) ); }

}

Page 7: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 7

Abstract Classes

• Classes must implement all methods.

• Interfaces must specify only the signatures of the methods.

• Abstract classes can implement some methods, leaving the rest to subclasses.

• Interfaces and abstract classes cannot be instantiated (to create objects).

Page 8: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 8

Arrays

• Index Range: 0 to (length - 1).• Each array object is of fixed size, permitting

index checking at run-time.

• int [] [] twoD = new int [8] [];• Point [] points = {new Point(5, 5), null };• twoD[1] = new int [2]; • twoD[1][0] = points[0].x;

Page 9: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 9

• Declaration– int[] intArray; – field intArray initialized to null, by default.

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

• Multi-dimensional array– double [][] iA = { { 1, 0 }, null };

• Java runtime verifies that array indices are in the correct range.

Page 10: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 10

Traditional First Program

public class HelloWorld {

public static void main(String [] args) {

System.out.println(“Hello World”);

}

}– javac HelloWorld.java– java HelloWorld a b c

Page 11: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 11

Another 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

Page 12: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 12

4 “a”

“c”

“23”

“abc”

args

(local variable on stack)

(array object on heap)

(string objects on heap)

Page 13: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 13

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];

}

}

}

Page 14: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 14

31

1

1

1

pT

(local variable on stack)

(array object on heap)

(int array objects on heap)

1

2

3

2

1

Page 15: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 15

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.

Page 16: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 16

Exceptions• Abnormal condition may be signaled by throw-ing

an exception. (Cf. Returning error (status) code that can be ignored by caller.)

• To deal with abnormal situation, the caller can provide an appropriate handler using try-catch construct.

• In Java, Checked Exceptions must be handled explicitly or propagated explicitly. (Errors and Unchecked Exceptions are propagated implicitly, if not handled explicitly.)

Page 17: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 17

Visibility of names

• Private:• class

• Default:• package (not just compilation unit)

• Protected:• package and subclasses (in other packages).

• Public:• where-ever the package is visible.

Page 18: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 18

Java Development Kit• java.lang (contains Threads)

• java.io (contains StreamTokenizer)

• java.awt (Abstract Windowing ToolKit)

• java.net (Support for TCP/IP, HTTP)

• java.applet (To run code via Browser)

• java.util (Standard Utilities)

• javac, java, javadoc

Page 19: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 19

Tokens

• Whitespace• blank

• tab

• newline

• Comment• // ...

• /* ... */

• /** ... */

• Separators• (, ), [, ], etc

• Keywords (reserved)• Identifiers• Literals

• 25, 2.5 (int/float)– 09 is not an integer.

• true, false (boolean)

• ‘a’, \u0061, \n (char)

• Operators• +, >, &&, etc

Page 20: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 20

Character Strings

class Stringclass StringBuffer

(Cf. array of characters)

Based on 2-byte Unicode characters

Page 21: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 21

class String vs class StringBuffer

• immutable– contents of String

instance unchangeable

– cannot insert or append characters

• fixed length

• s.length()– number of characters

in the string

• mutable– contents of

StringBuffer instance modifiable

• growable– grows automatically

when characters added

• sb.length()• sb.capacity()

– total allocated capacity

Page 22: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 22

String literals and concatenation• String s = “abc”;• System.out.println( s + “def” );

– “+” stands for string concatenation.– Built-in operator overload.

• Left associativity of “+”(s + 3 + 5) evaluates to “abc35”.

(s + (3 + 5)) evaluates to “abc8”.

(5 + 3 + s) evaluates to “8abc”.

• Assignments += 25;

Page 23: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 23

String conversions• class Object supports toString()-method

to convert a class instance into a printable string form: classname@hashcode

• toString() can be overridden. public String toString() { ... };

• println/print methods in System.out, the “+”-expressions, and the “+= ”-statements invoke toString() implicitly, to coerce an instance to a string.

Page 24: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 24

TYPE TO STRI NG FROM STRI NG

bool ean Stri ng. val ueOf (bool ean)new Bool ean(Stri ng).bool eanVal ue()

i nt Stri ng. val ueOf ( i nt) I nteger. parseI nt(Stri ng)

l ong Stri ng. val ueOf ( l ong) Long. parseI nt(Stri ng)

fl oat Stri ng. val ueOf (fl oat)new Fl oat(Stri ng).fl oatVal ue()

doubl e Stri ng. val ueOf (doubl e)new Doubl e(Stri ng).doubl eVal ue()

Page 25: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 25

Comparison

• “abc”.equals(“abc”) is true.• “abc”.equalsIgnoreCase(“ABC”) is true.• (s == s) is true.• (“abc” + s == “abc” + s) is false.• s1.compareTo(s2)

• negative: s1 lexicographically precedes s2• zero: s1 is equal s2• positive: s1 lexicographically follows s2

Page 26: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 26

Interningpackage testPackage;class Test {

public static void main(String[] args) {String hello = "Hello", lo = "lo";System.out.print((hello == "Hello") + " ");System.out.print((Other.hello == hello) + " ");

System.out.print((ext.Other.hello == hello)+" ");System.out.print((hello == ("Hel"+"lo")) + " ");System.out.print((hello == ("Hel"+lo)) + " ");System.out.println(hello == ("Hel"+lo).intern());

}}class Other { static String hello = "Hello"; }package ext;public class Other { static String hello = "Hello"; }

Result of execution: true true true true false true

Page 27: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 27

AssignmentString 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))

Page 28: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 28

Useful Methods– String t = “abca”; – String s = new String(t);

• s.charAt(2) is ‘c’.• s.indexOf(‘a’) is 0.• s.indexOf(“bc”) is 1.• s.indexOf(‘a’,2) is 3.• s.lastIndexOf(‘a’) is 3.• regionMatches, startsWith, endsWith, etc.

– Pure ASCII applications can be inefficient because Java uses 16-bit Unicode characters.

Page 29: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 29

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.

Page 30: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 30

variable reference object

(text) (pointer) (memory)

• Static Typing (e.g., Ada)• typetype(variable) = typetype(object)

• compile-time checking : efficient

• Dynamic Typing (e.g., Scheme)• variables type-less; objects carry type tags

• run-time type-checking : flexible

Typing

Page 31: CS 884 (Prasad)Java Examples1 Java Language Constructs

CS 884 (Prasad) Java Examples 31

• Typing in OOPL (E.g., Java, Eiffel, C++, …)• typetype(object/reference) is-a-subtype-of

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