1 / 138

.opennet Technologies Introduction to the Java Language and Object-oriented Concepts

.opennet Technologies Introduction to the Java Language and Object-oriented Concepts. Fall Semester 2001 MW 5:00 pm - 6:20 pm CENTRAL (not Indiana) Time Geoffrey Fox and Bryan Carpenter PTLIU Laboratory for Community Grids. Computer Science, Informatics, Physics Indiana University

edric
Download Presentation

.opennet Technologies Introduction to the Java Language and Object-oriented Concepts

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. .opennet TechnologiesIntroduction to the Java Language and Object-oriented Concepts Fall Semester 2001 MW 5:00 pm - 6:20 pm CENTRAL (not Indiana) Time Geoffrey Fox and Bryan Carpenter PTLIU Laboratory for Community Grids Computer Science, Informatics, Physics Indiana University Bloomington IN 47404 gcf@indiana.edu java-fall01

  2. Overview java-fall01

  3. What is Java, in a Nutshell? • What is Java? • A simple, object oriented, distributed, interpreted, robust, safe, architecture neutral, portable, high performance, multithreaded, dynamic, programming language. • Java is interesting because • It is both a general purpose object-oriented language along the lines of C++, and • It is particularly designed to interface with Web pages (Java on client) and to enable distributed applications over the Internet with Java on Server . • It has good software engineering properties • The Web is becoming the dominant software development arena; this is driving Java as perhaps the best supported, most widely taught language. • Even outside the Web, e.g. in scientific computing, Java is as good and in some respects better than other languages. java-fall01

  4. Architecture of Java (Client) Applications • Java applications are compiled and run on a machine just like any other general programming language such as C/C++. No web server or network are required although Java applications may also use network connections for distributed computing. • One can download dynamically for applets or servlets • There are also native (conventional) Java compilers Java code is compiled to produce byte code run by Java Virtual Machine (JVM) to produce results java-fall01

  5. Java Applications in a Nutshell • Java programs written in a file with extension “.java”. • Applications are .java files with a main() method. This is called by the Java system. • Compile and run a Java application (using bytecodes): • Run the compiler on a .java file: javac MyProgram.java producing a file of Java byte code, MyProgram.class • Run the interpreter on a .class file: java MyProgram which executes the byte code • The tools javacand java are part of JDK. java-fall01

  6. The Simplest Java Application: Hello,World! • Since Java is object-oriented, programs are organized into modules called classes, which may have data in variables called fields, and subroutines called methods. Each program is enclosed in a class definition. main() is the first method that is run. class HelloWorld { public static void main (String[] args) { System.out.println(“Hello World!”); } } The notation class.method or package.class.method is how to refer to a public method (with some exceptions). Syntax is similar to C - braces for blocks, semicolon after each statement. java-fall01

  7. Java vs. JavaScript • Despite the name, JavaScript is a different language from Java, albeit with some similarities. • A JavaScript program is written directly in the HTML page, and executed by the JavaScript interpreter, so also allows dynamic web page content in the browser window. • JavaScript is special purpose - it is an object-based language that deals directly with browser entities like windows, text fields, forms, frames and documents. • JavaScript can respond to browser events like mouse clicks and user-typed text. • JavaScript is fast to write, but not as powerful as Java. java-fall01

  8. Multi-tier Architecture • Distributed applications on the web naturally have a multi-tier architecture. • Java plays a role at all three levels: • Graphical User Interface and client side analysis systems, including visualization • Middle layer servers and software integration, including web servers, distributed object servers and other application servers. • Less important for back end client software, which may be legacy code. Internet Client user interface running through browser Internet or proprietary network Middle level servers Backend computing or databases java-fall01

  9. History of Java Language and Team • Starts in 1991 as Project Green—semi-autonomous task force in Sun focusing on operating software for consumer electronic devices, e.g. smart set-top boxes. • Gosling (creator of Sun NeWS) considers C++ too complex and initiates development of Oak, later renamed to Java. Similarities to UCSD P-system. • A PDA (Personal Digital Assistant), codename “*7”, based on Oak/Java ready in 1993. Green Team becomes FirstPerson, Inc. • *7 proposal to Time-Warner rejected in 1993. 3DO deal falls through in 1994. FirstPerson, Inc. dissolves. • Small group (~30 people, becomes the Java Team) continues and decides to adapt Oak as a Web technology. java-fall01

  10. History of Java Language and Team to Dec. 95 • Experimental Web browser written in Java, called WebRunner, later renamed HotJava, ready in 1994. • Alpha release of Java and HotJava April '95. • Netscape licenses Java in May '95 and builds Java into Netscape 2.0 • Beta Java Development Kit (JDK) and first Java books Summer/Fall '95. • Dec 4, 1995 Business Week cover story: "Software Revolution—The Web Changes Everything" presents Java as a breakthrough force in the expanding Web/Internet. • In next week, SGI, IBM, Adobe, Macromedia and finally Microsoft adopt/license Java. Java is adopted by Web community. • The rest is as they say history ………………….. java-fall01

  11. Java Features—Simple and Familiar • Familiar as it looks like C++, but simpler to program. • omits several confusing features of C++ including operator overloading, multiple inheritance, pointers and automatic type coercions • Adds automatic garbage collection to make dynamic memory management much easier than in C or C++. • No more frees or deletes. No more memory leaks. • Adds Interface construct, similar to Objective C concept, to compensate for the lack of multiple inheritance. • Small kernel is suitable for Java ports to consumer electronic devices. • But need customization J2ME to be effective (remove unnecessary features and support special capabilities of PDA’s etc.) java-fall01

  12. Java Features—Architecture-Neutral • C/C++ programming in a heterogeneous network environment demands compatibility across several vendor platforms and their compilers. • Solved in Java by designing platform-independent binary representation called Java bytecode—comparable to P-code in UCSD Pascal. • Java compiler reads Java source and generates Java bytecode, which is shipped to user. • Each client must have a Java Virtual Machine program, which interprets (“runs”) Java bytecodes. java-fall01

  13. Java Features—Robust • Java enforces compile-time type checking and this eliminates some error prone constructs of C/C++. • Pointer arithmetic is eliminated which allows for, e.g., runtime checking of array subscripts, and enforces security of the Java model. • Explicit declarations are always required; argument types of methods are always checked (unlike C). This allows the Java complier to perform early error detection. • Java is most secure of popular languages because it is strict and security was built in java-fall01

  14. The Java 2 Platform Sun are now offering 3 “editions”: • Java 2 platform, Standard Edition (J2SE) • Refines earlier JDKs • Available in version 1.4. • Java 2 platform, Enterprise Edition (J2EE) • Incorporates multiple technologies for server-side and multi-tier applications. • Java 2 platform, Micro Edition (J2ME) • Optimized run-time environment for consumer products. java-fall01

  15. Installing JDK • Become administrator (for Windows) or root (for Linux, etc.) • This is recommended though probably not essential. • Go to http://java.sun.com/j2se/1.4 • Select “Download Java 2 SDK, standard edition, v1.4.x,” for Windows or Linux, etc. • Download the software, then read http://java.sun.com/j2se/1.4/install-windows.html or http://java.sun.com/j2se/1.4/install-linux.html, etc. • Pay attention to instructions for setting PATH. • These give a command line interface for the Java compiler javac and the Java interpreter (JVM driver) java, etc. • If you are familiar with UNIX environments, but want to use these commands from Windows, consider installing Cygwin: www.cygwin.com. java-fall01

  16. Java Books—I • Core Java, by Gary Cornell andCay S. Horstmann, offers detailed coverage of the whole language and packages for advanced programmers, including the Swing Set. (We will not cover these user interface issues here) Also Volume 2 gives good coverage of advanced topics such as JDBC, RMI, JavaBeans and security. • Java, How to Program, by Deitel and Deitel, Prentice-Hall, starts with beginning programming concepts and progresses rapidly through Java language. It has the most programming exercises and also has companion teaching multimedia books. The third edition has Swing Set and also the advanced API’s. java-fall01

  17. Java Books—II • The Java Programming Language, by Ken Arnold and James Gosling, David Holmes, 3rd Edition, Addison-Wesley, 2000, is the classic on the language basics for intermediate and advanced programmers. It covers threads and I/O packages, but not applets or windowing packages. • Java in a Nutshell, by David Flanagan, is the language reference book in the familiar O'Reilly series. One of the better references. Also Java Examples in a Nutshell. • The Java Language Specification, second edition. James Gosling, Bill Joy, Guy Steele, Gilad Bracha, April 2000. The ultimate reference for hardened computer scientists/compiler writers. java-fall01

  18. Resources for the Java Programming Language • http://java.sun.com web site has plenty of references including • Tutorial:http://web2.java.sun.com/docs/books/tutorial • Books:http://web2.java.sun.com/docs/books • Collection of Java Resources: http://www.gamelan.comhttp://www.jroundup.com/ java-fall01

  19. Java Language Basics java-fall01

  20. Obvious similarities to C, C++ • Java syntaxhas many similarities to C, C++. • All variables must be declared • Syntax of expressions and control structures almost identical to C, C++ • C or C++ style comments allowed. • For Fortran programmers, syntax is a bit different (; to end line { …} to delineate blocks ) for basic material. Fox thinks “structured programming syntax more natural than Fortran 90. • Arrays not as good for Science as those in Fortran • No Array syntax as in Fortran90 java-fall01

  21. Obvious differences from C, C++ • No low-level pointers or pointer arithmetic. • Instead have variables and expressions of reference type. • No malloc() or free() to allocate more memory for dynamically created data structures—instead have a “new” operator for creating objects, plus automatic garbage collection. • Can declare variables almost anywhere (like C++). • No struct, union, enum, typedef—classes and objects are used uniformly instead. java-fall01

  22. Primitive types rationalized • Java characters use 16-bit Unicode Worldwide Character Encoding instead of 8-bit ASCII. Supports all alphabets and languages. • Primitive types for integers and floats have machine independent semantics. • Boolean expressions in Java have value “true” or “false” (not 0, 1, . . .) java-fall01

  23. Three kinds of comments in Java • /* ignore all between stars */ • As for C • // ignore all till the end of this line • As for C++ • /** this is a documentation comment */ • Should appear immediately before, e.g., class or method definition, and describe intended use. java-fall01

  24. Documentation Comments • Used by documentation-generating tools like javadoc to produce documentation, typically in HTML form. • Optionally include formatting tags like @param, which flags a description of a method parameter: /** This method does what it feels like. @param bar This is a pointless argument. */ void foo (int bar) {. . .} • Other formatting tags include @returns which flags a description of a method result value, or @see name, which creates a hypertext link toname. java-fall01

  25. Java Keywords • Java reserves the following keywords: • goto is not allowed in Java, but it’s still reserved (to protect Fortran programmers)! • null, true, and false are literals with special meaning. java-fall01

  26. Java Language—Program Structure • Source code of a Java program consists of one or more compilation units, each implemented as a file with extension “.java”. • Each compilation unit can contain: • a package statement • import statements • class declarations and/or interface declarations. • In typical Java development environments, exactly one of the class (or interface) declarations in each compilation should be marked public. • The file should be named after the public class. e.g. if the public class isFoo, the file name should be “Foo.java”. java-fall01

  27. Java Types • Each Java variable or expression has a definite type, given by a declaration such as int i; double x, y, z; Color c; • There are two sorts of type: • Primitive types like ints or booleans are built into the language. • Reference types.These include class types like Color, and array types (and also interface types). java-fall01

  28. Primitive Types • There are 4 integer types: byte short int long Sizes are 8, 16, 32 and 64 bits, respectively. • float is 32 bits, double is 64 bits. Floating point arithmetic and data formats are defined by IEEE 754 standard. • char format is defined by 16 bit Unicode character set. • booleanis eithertrue or false. • One can use casts for arithmetic conversion, as in: int i ; float x ; i = (int) x ; java-fall01

  29. Reference Types • These are the types associated with composite entities like objects and arrays. • They are called reference types because a variable or expression in a Java program with reference type represents a reference (or pointer) to a composite entity. • Any variable of reference type may take the value null. • Reference types can be divided into: • Class types • Interface types (discussed later) • Array types java-fall01

  30. Strings—an Example of a Class Type • Java environments provide predefined classes for common data types. Every Java environment provides a String class. • Declaration of a String variable looks like: String s ; // variable declaration • The variable declaration itself doesn’t create any objects. We can create a new String object by, e.g.: s = new String(“This is the text”) ; // object creation • These may be combined on one line: String s = new String (“This is the text.”) ; java-fall01

  31. A Constructor Function • In the object creation expression: new String (“This is the text.”) the term String (“This is the text.”) is a constructor invocation. • All classes have special “functions” called constructors. These functions have the same name as the class. They initialize the fields of the object. • Constructor functions are only used in object creation operations—nearly always directly after a new operator. • In this example the constructor has one argument: a string literal. • We will see later that in general constructors can have arbitrary argument lists. java-fall01

  32. Some features of Strings. • Strings are Java objects, but Java provides some syntax peculiar to strings. • In fact literal string in double quotes itself refers to a pre-existing String object—so in practice we may drop new operation for string constants: String s = “This is the text.” ; • After creation, characters of a string object neverchange. • In other words: string objects are immutable. java-fall01

  33. Operations on Strings. • Although a String object is immutable, String-valued variables can be reassigned to refer to new string objects: String str = “Chicken soup with rice” ; int n = str.indexOf( ‘w’ ) ; str = str.substring(0,n) + “is n” + str.substring(n+6) ; // Result: “Chicken soup is nice”. • The operator + is used for concatenation(special syntax for strings). • indexOf() and substring() are methods of the String class— and are not a special syntax! • They illustrate the general syntax of method invocation on an object. java-fall01

  34. Array Types • As for objects, declaring an array variable is distinct from creating on the array: int states[] ;// variable declaration and: states = new int[128] ; // array creation • Again, these can be combined: int states[] = new int[128] ; • Alternative (better?) syntax for declaration: int[] states ; java-fall01

  35. Subscripts • With states is declared as above: int states[] = new int[128] ; it can be subscripted by integersfrom 0 to 127. • Subscripts are checked at runtime: states[-1] or states[128] will immediately generate exceptions. • This subscript checking is an example of where Java trades robustness for performance • Array length is given by the length instance variable:int len = states.length ; // assigns len = 128 • One cannot change the length of an Array – the Java vector class is designed for this java-fall01

  36. Arrays of Objects • Arrays of arbitrary objects can be constructed, e.g.: Color manycolors[] = new Color[1024]; • This creates an array of object references. It does not create actual objects for individual elements. • Before you use the array elements, you may need to use object constructors to allocate each object, e.g.: for (int i = 0 ; i < 1024 ; i++) manycolors [i] = new Color() ; java-fall01

  37. Multidimensional Arrays • Multidimensional arrays are arrays of arrays. In general these arrays may be “ragged”: int graph[][] = new int[2][]; graph[0] = new int[4]; // Row 0 has length 4 graph[1] = new int[7]; // Row 1 has length 7 . . . graph[1][1] = 9; • Shorthand syntax for creating a rectangular array: char icon[][] = new char [16][16]; // 16 by 16 array • Note icon is still logically an arrays of arrays, and nothing in Java forces it to stay rectangular. E.g. later someone might doicon [8] = new char [17] ; // Now ragged! • Does not violate rule that Array lengths constant as icon [8] points to a new array of length 17. java-fall01

  38. Java Language—Expressions • Most Java expressions are similar to C or Fortran. Here are some examples: • arithmetic: 2 + 3 (2 + 3) * i • auto-increment and decrement: i++ // equivalent to i = i +1 • Boolean: ((i > 0) && (j > 0)) || (state == –1) • bit operations: i << 1 // Shift bit pattern 1 place left • conditional expression: (i > 0) ? expression1 : expression2 False True java-fall01

  39. Java Language—More Expressions • Java has some expressions of its own: • string concatenation: “fred” + “jim” // Value is “fredjim” • object “instance of” test: (a instanceof B) //true iff object ahas type (class) B java-fall01

  40. Java Control Flow. I: if Statements • Conditional execution of statements: if (some Boolean expression) { statements to be executed if true } • Optional else clause: if (some Boolean expression) { statements to be executed if true } else { statements to be executed if false } • Nested example: if (some Boolean expression) { . . . } else if (another Boolean expression) { . . . } else { . . . } java-fall01

  41. Control Flow II: while Loop Constructs • Normal while loop: while (any Boolean) { Stuff to do } Example: int i = 0 ; while(i < a.length) { a [i] = i * i ; i++ ; } • whileloop with test at end: do { What to do } while (another Boolean) ; java-fall01

  42. Control Flow III: The for Loop Construct • In Java, most often one uses the C++-like variant (cf. DO loops in Fortran): for (declaration1; booleanExpression; expressionList2) { Statements to do } The declaration declaration1 is effected at start of loop, comma-separated expressionList2 is evaluated after every iteration, and the loop terminates when booleanExpression is false. • Typical example: for (int i = 0 ; i < a.length ; i++) a [i] = i * i ; • The original C-like form (no declaration) also available: for (expressionList1 ;booleanExpression;expressionList2) { Statements to do } java-fall01

  43. Control Flow IV: The switch Construct • Identical to C: switch (expression) { caseConstant1: // Do following if expression==Constant1 Bunch of Stuff break; caseConstant2: // Do following if expression==Constant2 Bunch of Stuff break; default: // Do the following otherwise Bunch of Stuff break; } java-fall01

  44. Control Flow V: break and continue • Unlabeled breakstatement immediately exits the enclosing switch, while, do or forconstruct: while (true) if (++i == a.length || a[i] == v) break ; • Labeledbreakstatement allows to exit an arbitrary enclosing statement, provided it is labeled: assign: { if (i >= a.length) break assign ; a[i] = v ; } (This is not the best way to do this!) • Thecontinuestatement skips to the end of the current iteration of the enclosingwhile, doorfor. java-fall01

  45. The Java Object Model: Classes, Instances and Methods java-fall01

  46. The Java Object Model Overview • Programs are composed of a set of modules called classes. Each class is a template specifying a set of behaviors involving the data of the class. • Each class has variables, or fields,to hold the data, and methods—akin to functions or procedures in other languages—to define the behaviors. • Each object in a program is created as an instance of a class. Each class instance has its own copy of the instance variables defined for the class. • Classes can be used for data encapsulation, hiding the details of the data representation from the user of the class (e.g., by marking variables as private). Instance Variables Methods java-fall01

  47. Defining a Class • A class declaration consists of: • a header giving the class name, modifiers, and possible superclass and interface structure. and a class body usually containing: • declarationsof fields (possibly with initializations)—class variables and instance variables. • declarations of methods. • declarations of constructors. These “functions” look like methods, but have the same name as the class. They do initialization when objects—class instances—are created. • nested class and interface definitions. • class or (rarely) instance initialization statements. java-fall01

  48. Example: a Predefined Class • A (small) part of the Java Date class: public class Date implements Serializable, Cloneable { public Date( ) {. . .} // Constructor public Date(long msSinceEpoch) {. . .} // Constructor public int getTime( ) {. . .} // Accessor public void setTime(long msSinceEpoch) {. . .} // Mutator public boolean after(Date when) {. . .} // Comparision public boolean equals(Object obj) {. . .} // Comparision . . . } • Note: all variables, methods and constructors visible from “outside” the class—parts of Datethat programmers writing code in other classes are allowed to use—have the publicmodifier in their declaration. java-fall01

  49. Creating a Class Instance • The Date class represents a particular date and time, with a resolution of milliseconds. • The first of the two Date constructors (“no-argument constructor”) constructs an instance of the Date class and sets its value to the current moment: new Date() • Constructors (like methods) can be overloaded. Constructors of same name are distinct if they have distinct argument types. If ms is a long, the object: new Date(ms) represents a moment ms milliseconds after January 1, 1970, 00:00:00 UTC (Coordinated Universal Time). • Java will become obsolete (2^63 – 1) / 1000 seconds after that (approximately 292 million years AD, UTC). . . java-fall01

  50. Example of Using a Class • An example application using a method of the Dateclass: import java.util.Date; public class DateTest { public static void main (String[ ] args) { Date early = new Date(1000) ; // very early seventies! Date today = new Date() ; // Now! if (today.after(early)) System.out.println( "Today is not early!") ; } } java-fall01

More Related