310 likes | 602 Views
Java Examples. Java Language Constructs. 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).
E N D
Java Examples Java Language Constructs Java Examples
Java Program Organization • Compilation Unit= File • Package = Directory • AJava programis a set of compilationunits organized using a package hierarchy (that is, as a forest of trees). • Acompilation unitis a set ofclassandinterfacedeclarations. • Every compilation unit belongs to a unique (possibly unnamed) Java package. Java Examples
Every file (compilation unit) can haveat most onepublic class. • The definition ofpublic classPCmust be in a file namedPC.java. • Set environment variablesCLASSPATH and PATHappropriately. • To compile: > javac PC.java • To run: > java PC • To run applets: > netscape PC.html > appletviewer PC.html Java Examples
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 Java Examples
Interface Declaration interfaceTable{ booleanisEmpty(); voidinsert(Object x, int key); ObjectlookUp(intkey); } • An interface specifies constants and signatures of the methods. • An interface can extend several super-interfaces. Java Examples
Class implements Interface import java.util.Hashtable; classIndeximplementsTable{ HashTablev = newHashtable(); publicbooleanisEmpty() { returnv.isEmpty(); } publicvoidinsert(Objectx, intkey) { v.put(newInteger (key) , x); } public ObjectlookUp(intkey) { returnv.get(newInteger ( key )); } } Java Examples
Abstract Classes • Classesmust implementall methods. • Interfacesmust specify only the signaturesof the methods. • Abstract classescanimplement some methods,leaving the rest to subclasses. • Interfaces and abstract classes cannot be instantiated (to create objects). Java Examples
Arrays • Index Range:0to(length - 1). • Each array object is of fixed size, permitting index checking at run-time. • int [] []twoD = newint[8] []; • Point [] points = {newPoint(5, 5), null }; • twoD[1] = newint [2]; • twoD[1][0] = points[0].x; Java Examples
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. Java Examples
Traditional First Program public classHelloWorld{ public static voidmain(String [] args) { System.out.println(“Hello World”); } } • javac HelloWorld.java • javaHelloWorld a b c Java Examples
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 Java Examples
4 “a” “23” args “c” “abc” (local variable on stack) (array object on heap) (string objects on heap) Java Examples
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]; } } } Java Examples
3 1 1 2 1 pT 1 (int array objects on heap) 3 1 (local variable on stack) 2 (array object on heap) 1 Java Examples
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. Java Examples
Exceptions • Abnormal condition may be signaled by throw-ingan exception. (Cf. Returning error (status) code that can be ignored by caller.) • To deal with abnormal situation, the caller canprovidean appropriate handler using try-catchconstruct. • In Java, Checked Exceptions must be handled explicitlyor propagated explicitly. (Errors and Unchecked Exceptions are propagated implicitly, if not handled explicitly.) Java Examples
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. Java Examples
Java Development Kit • java.lang (containsThreads) • java.io(containsStreamTokenizer) • java.awt (Abstract Windowing ToolKit) • java.net(Support forTCP/IP, HTTP) • java.applet (To run code via Browser) • java.util(Standard Utilities) • javac, java, javadoc Java Examples
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 Tokens Java Examples
Character Strings class String class StringBuffer (Cf. array of characters) Based on 2-byte Unicode characters Java Examples
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 class String vs class StringBuffer Java Examples
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”. • Assignment s += 25; Java Examples
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. Java Examples
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 Java Examples
Interning package 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 Java Examples
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)) Java Examples
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. Java Examples
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. Java Examples
Typing variablereferenceobject (text) (pointer) (memory) • Static Typing (e.g., Ada) • type(variable) = type(object) • compile-time checking : efficient • Dynamic Typing (e.g., Scheme) • variables type-less; objects carry type tags • run-time type-checking : flexible Java Examples
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. Java Examples