1 / 31

Java Examples

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

art
Télécharger la présentation

Java Examples

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Examples Java Language Constructs Java Examples

  2. 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

  3. 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

  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 Java Examples

  5. 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

  6. 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

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

  8. 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

  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. Java Examples

  10. Traditional First Program public classHelloWorld{ public static voidmain(String [] args) { System.out.println(“Hello World”); } } • javac HelloWorld.java • javaHelloWorld a b c 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 Java Examples

  12. 4 “a” “23” args “c” “abc” (local variable on stack) (array object on heap) (string objects on heap) 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]; } } } Java Examples

  14. 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

  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. Java Examples

  16. 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

  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. Java Examples

  18. 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

  19. 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

  20. Character Strings class String class StringBuffer (Cf. array of characters) Based on 2-byte Unicode characters Java Examples

  21. 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

  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”. • Assignment s += 25; 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. Java Examples

  24. 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 Java Examples

  26. 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

  27. 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

  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. 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. Java Examples

  30. 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

  31. 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

More Related