1 / 111

GSAMS’ Un distinguished Lecture Series presents . . .

GSAMS’ Un distinguished Lecture Series presents . . . Java for the Impatient. WHO. Russ Shackelford, B.A., M.A., M.S., Ed.S., Ph.D. David Dagon, B.S., J.D., etc. . @. russ@cc.gatech.edu dagon@cc.gatech.edu. WHAT. Covers essential Java syntax and debugging techniques.

arch
Download Presentation

GSAMS’ Un distinguished Lecture Series presents . . .

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. GSAMS’Undistinguished Lecture Seriespresents . . . Java for the Impatient

  2. WHO Russ Shackelford, B.A., M.A., M.S., Ed.S., Ph.D. David Dagon, B.S., J.D., etc. @ russ@cc.gatech.edu dagon@cc.gatech.edu

  3. WHAT Covers essential Java syntax and debugging techniques Presumes familiarity with computer, and an IDE or text editor David Dagon: Georgia Tech’s introductory computing course has the students use NTEmacs with JDE to edit their code. You can get a copy of this distribution at: http://www.cc.gatech.edu/classes/cs1502 Look for the links on “Help with IDEs”

  4. A Note on Noise • Some noise is good • We must share the medium, and should be aware of others. • However, please feel free to ask questions

  5. What is Java? "A simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language” -- Sun Sounds like marketing; let’s take a closer look . . . David Dagon: FYI. The next set of slides give a brief explanation of each of these terms. Some of the slides introduce some complicated subjects; future sets of slides will cover them in greater detail.

  6. “… object oriented …” • Java is an “object oriented” (or “OO”) language. • It is possible (but seldom desirable) to write non-object oriented Java code (so-called “hybrid OO”). • In an OO language, classes are used to encapsulate data (state) and behavior. • Instances of a class are then used to manipulate data and drive the program. • Classes are arranged in an hierarchy, or package structure.

  7. “… object oriented, …” Example: A “Stack” is a class found in the package java.util. We create an instance of the class Stack using the keyword new thus: import java.util.*; Stack c = new Stack(); c.push(“3”); java.util.Stack x = new Stack(); David Dagon: It’s difficult to come up with a simple example of an object. One might use java.lang.String; however, there are some exceptions to String creation built into Java. One could also use the java.lang.Integer class; however, this presumes some knowledge of wrapper classes. Note also that I’ve called the Stack in this example “c”, instead of “myStack” or something similar. It’s very common to use the ‘my-’ prefix in object creation; however, those not used to OO language might find it confusing. To emphasize that the Stack instance is merely an object, we use the familiar variable ‘c’. Of course, we could have called the Stack “foo”. This differs from procedural (e.g., C) and functional languages (e.g., Lisp) where other data structures would be used to model the Stack. More on classes in later slides . . .

  8. “… distributed, …” Java is also a distributed language. It was built with networking in mind Fully supports IPv4, with structures to support IPv6. Includes support for “Applets”: small programs embedded in HTML documents. See: java.net package RMI/CORBA David Dagon: Java provides convenient access to the OSI Network layer. Other APIs allow one to access even lower layers.

  9. “… interpreted, …” Java is an interpreted language, meaning that each instruction is translated into machine code at the time of execution, not during compilation. This allows for platform neutrality: “WORA” This allows one to rewrite and change a program while it is running. Penalty: speed

  10. “… robust, …” Java is simple--no pointers/stack concerns (for the most part) In-bound checking at runtime of array pointers--no memory corruption and cryptic error messages. Exception handling: try/catch /finally series allows for simplified error recovery Strongly typed language: many errors caught during compilation.

  11. “… secure, …” • Byte-code verification on loading (not just compilation). • Applet code runs in 'sandbox', with significant restrictions • Security is enforced by the • SecurityManager class • Work-arounds for applet • security restrictions include • digitally signing code, and • Servlets

  12. Evaluation of Java • Strengths of Java: • A real language, in demand in industry • Portability • Comparatively easy to learn • Difficult to destroy a machine with it ;-) • Advanced built-in GUI/Graphics features • Weaknesses of Java: • Slow: interpreted and OO • GUI/Graphics via “Least Common Denominator” approach (due to platform independence) • Awkward/annoying syntax

  13. Structure of Java Programs • Applications (“normal” computer programs): • Each program consists of multiple files. • Each file contains a class. • First method (module) called is: public static void main(String[ ] argv) • The main method controls program flow (but OO orientation means that it starts a process that features decentralized control).

  14. Structure of Java Programs • Applets (transportable over WWW): • Similar to applications, but... • First method is: public void init( ) • Remainder of applet is a series of handlers that respond to events (e.g., user actions). • Program is executed by Java interpreter running in Web browser or applet viewer.

  15. Sample Program (in a file called “HelloWorld.java”) public class HelloWorld { public static void main(String argv[]) { System.out.println(“Hello World!”); } }

  16. Basic Syntax All java programs contain (within one or more* classes): public static void main (String a[ ]) { ... } The Java interpreter runs until the main() returns, a System or Runtime exit is called, a fatal error occurs, or until the end of main is found. David Dagon: The following slide is the traditional HelloWorld program. Note that white space is irrelevant. Also note that the naming of local variables is arbitrary (compare a[ ] to arg[ ]).

  17. import java.lang.Runtime; /* not necessary */ class GoodByeWorld { public static void main (String arg[]) { Runtime.getRuntime().traceInstructions(true); Runtime.getRuntime().traceMethodCalls(true); System.out.println (”Here’s some stats:"); System.out.println (Runtime.getRuntime().totalMemory() + " total memory\n” + Runtime.getRuntime().freeMemory() + " available"); if (true) return; /* 1 */ System.exit(0); /* 2 terminates */ Runtime.getRuntime().exit(0); /* 3 terminates only if the thread is running */ } /* 4 --end of main*/ }//test GoodBye World

  18. Vocabulary • Structured Programming: • A programming paradigm in which the actions (or verbs, or procedures) are emphasized. • OO Programming: • A programming paradigm in which the actors (or nouns, or objects) and their interaction is emphasized. • Byte Compiler: • A compiler which translates human-readable source code into byte code (transportable to various virtual machines) instead of object code written for a specific kind of machine.

  19. Vocabulary (cont’d) • Byte Interpreter: • An interpreter which translates byte code into object code for a particular kind of machine and executes them on that machine. • Byte Code: • An instruction for a virtual machine. • Java Virtual Machine (JVM): • The virtual machine (software) for which all Java programs are compiled. A byte code interpreter is required to translate from the JVM byte code instructions into to instructions for a given actual machine.

  20. Java’s Popularity • Keys to Java’s Popularity: • An OO language that’s relatively simple. • Virtual Machine approach, allowing transportability to various different kinds of computers (operating systems). • Presence of JVM as part of Web browsers, encouraging movement of Java programs over the Web.

  21. Java is not a purely OO language, and supports several primitive data types, including: Primitives • Primitive Type Default Value • boolean false • char '\u0000' (null) • byte (byte) 0 • short (short) 0 • int 0 • long 0L • float 0f • double 0d • void N/A David Dagon: According to the Java Language Specification, void is a primitive. But introducing void to students might be confusing. We include it here to be complete; in teaching, you might omit this 9th primitive

  22. Variable Declarations • Java: • <datatype> <identifier>; • or (optional initialization at declaration) • <data type> <identifier> = <init value>; int x; x = 3; int y = 5;

  23. Naming Conventions • Begin variable identifiers with abbreviation of their type: • i for int (integer) • f for float • b for boolean • ch for char • str for String

  24. Examples • int iCounter; • int iNumStudents = 583; • float fGPA; • float fBatAvg = .406; • char chGender; • char chGender = ‘f’; • boolean bSafe; • boolean bEmpty = true; • String strPersonName • = “Fred”; • String strStreetName;

  25. Operators • Assignment: = • Arithmetic: +, -, *, /, % (mod) int iNumLect = 2; int iNumStudents = 583; int iStudentsPerLect; iStudentsPerLect = iNumStudents / iNumLect; // gives 291 due to integer division int iNumQualPoints = 30; int iNumCreditHours = 8; float fGPA; fGPA = iNumQualPoints / iNumCreditHours; // gives 3.0 due to integer division iVar = iVar * flVar // gives compile-time error

  26. Shorthand Operators • iCounter = iCounter + 1; OR iCounter++; • iCounter = iCounter - 1; OR iCounter--; • iCounter = iCounter + 2; OR iCounter+=2; • iCounter = iCounter * 5; OR iCounter*=5; • latter 2 examples: • it’s “op” then “equals” (e.g., +=2), not “equals” then “op” (e.g., isn’t =+2)

  27. worthless Good for blocks Never closed Some Comments on Comments • 1. C-style comments with /* */; no nesting • 2. C++ style comments beginning // • 3. A unique "doc comment" starting with /** ...*/ • Fun with comments: • /*/ • /* // */ • /////////////////// • /* ========= */

  28. Javadoc /** * <PRE> * getName(int i) - returns the name at a * specified array location * </PRE> * @param int i - the index of the array to * be retrieved * @return String strName - the name * @see Employees#isEmployed() - called to * verify employment */ public String getName (int i) { if (myEmpl.isEmployed()) return myArray[i]; else return "Nada"; } // getName(int) David Dagon: Javadoc can generate an API listing of your code

  29. You may include HTML tags (but avoid structuring tags, like <H1>, etc.) • Javadoc comments should immediately preceed the declaration of the class, field or method. The first sentence should be a summary. Use the special javadoc tags--@. When '@' tags are used, the parsing continues until the doc compiler encounters the next '@' tag. Javadoc (Cont’d) @ see <class name> @ see <full-class name> @ see<full-class name#method.name> @ version David Dagon: The @deprecated tag interacts with the compiler to turn off warnings. @author @param @return @exception @deprecated // jdk 1.1 @since // jdk 1.1 @serial // jdk 1.2

  30. Constants • Valid: • public final <type> <IDer> = <value>; • Preferred: • public final static <type> <IDer> = <value>; • public final static int • iMIN_PASSING = 60; • public final static float fPI = 3.14159; • Details on “why this syntax” to come soon...

  31. Printing to Screen • Various techniques: • System.out.println(<arguments>); • System.out.println( ); // prints blank line • System.out.println(5); // prints 5 • System.out.println(“Hello World”); // prints Hello World • “println” vs. “print” in Java: • println includes “carriage return” at end, next print or println on new line • print causes next print or println to begin at next location on same line

  32. Printing (cont’d) • When starting Java, there are at least three streams created for you: System.in // for getting input System.out // for output System.err // for bad news output • These are InputStream and PrintStream objects • Note: For Win95/NT System.out is "almost" identical to System.err - the both display to the screen (the one exception is when using DOS redirect, >, where System.out is redirected, while System.err is still put to the screen )

  33. Printing (cont’d) System.out.println ("This line is printed out") System.err.println ("This is the error stream's output"); These are both instances of the PrintStream class. There are other methods you might find useful in these classes: System.out.flush(); System.out.write(int); System.out.write(byte[] buf, int offset, int length);

  34. Pseudocode: if (condition) then statements else other statements endif Java: if (condition) single statement; else single statement; or: if (condition) { statements; } else { statements; } Decision Statements

  35. Conditional Assignment <boolean> ? <true condition> : <false condition> boolean b; int iCount; b = checkCompletion(); iCount = (b) ? 3 : 1; Must resolve to boolean If true . . . . . . if false

  36. Pseudocode: test_grade isofftype Num ... is_passing isoftype Boolean is_passing <- TRUE if (test_grade < 60) then is_passing <- FALSE endif print (is_passing) Java: what happens here? boolean bPassing = true; int iTestGrade; ... if (iTestGrade < 70) bPassing = false; System.out.println (bPassing); Examples

  37. Boolean and Relational Operators • Boolean: Pseudocode: Java: AND AND && OR OR || NOT NOT ! • Relational equal to = = = not equal to <> != less than < < less than or equal to <= <= greater than > > greater than or equal to >= >=

  38. Errors • Compile-time errors: • Syntax errors: illegal language statements • Certain kinds of semantic errors.e.g., type mismatch (assign a Character value to Boolean var) • Run-time errors: • Certain kinds of semantic errors.e.g., try to access non-existent dynamic data (dereference a nil/null pointer) • Logic errors: legal program that produces wrong behavior

  39. Debugging Strategies • Compile-time errors: • The compiler will yell at you about them. • BUT . . . industry research shows . . . • It is a time-waster to: • code sloppy • use the compiler to find your mistakes • It is faster to: • check the “annoying details” of your code to catch them BEFORE compilation. • Lesson: don’t become a compiler junkie!

  40. Debugging Strategies • Run-time errors: • Programming environment provides tools for tracing values as code executes. • But: the most basic tools are independent of the programming environment: • 1. Code tracing: use your eyes and mind! • 2. Use print statements: insert statments that tell you what key values are at given points in your program. • 3. Use DEBUG flags: build in print statements in a way that lets you turn them on and off.

  41. The “DEBUG” Flag Idea • In Pseudocode: // in the main DEBUG is TRUE // or FALSE // inside of procedure This_Proc . . . if DEBUG then print (“am entering proc This_Proc”) print (“this_param: “, this_param:) print (“that_param: “, that_param:) endif // code goes here if DEBUG then print (“am leaving proc This_Proc”) print (“this_param: “, this_param:) print (“that_param: “, that_param:) endif

  42. The “DEBUG” Flag Idea • In Java: public static final boolean DEBUG = true; … public void myMethod() { if (DEBUG) System.out.println (“Entering myMethod()”); … if (DEBUG) System.out.println (“Leaving myMethod()”); }

  43. Java File Names Source code files must have the ".java" extension. The file name should match the class name. This naming convention is enforced by most reasonable compilers. Thus, an improperly named java file, saved as "myTest.java": class test { ... } Compiled byte code has the ".class" extension.

  44. Java File Structure • Java Files: • 1. Consist of the optional package statement, • 2. followed by any necessary import statements • 3. followed by the class name, • 4. followed by any inheritance • and interface declarations. • 5. Note: if the file defines more than one • class or interface, only one can be declared • public, and the source file name must match • the public class name.

  45. Thus: • package edu.gatech.cc.dagon.gsams-java; • import java.util.*; • import edu.gatech.cc.dagon.gsams-java.hashtable.*; • import netscape.javascript.JSObject; • import netscape.javascript.JSException; • public class SplayTree implements TreeType, TreeConstants • { ... • }// SplayTree • Note the globally unique • package name. Without a • package specification, • the code becomes part of an • unnamed default package in • the current directory. An Average Java File

  46. Import Statements • Import statements Come in three flavors: • import package.class; // 1 • import package.*; // 2 • import java.lang.*; // 3 (Implicit) • What it does: provides the Java interpreter with a reference to other classes necessary • for the compilation of the • present .java file • What it does NOT: actually • "import" or ”#include" the • code. There’s no overhead • or object bloat.

  47. Why No #include statements? • Java maps fully qualified class names to a directory path, and therefore does not need an #include, #ifdef, etc. (and no preprocessor as well) • Thus: • java.awt.TextField • is mapped to: • java/awt/TextField • and dynamically loaded, • as needed. David Dagon: This explains the mystery behind the error message reported when one attempts to run a file with the “.class” extension passed into the java VM: java FooBar.class Exception in thread "main" java.lang.NoClassDefFoundError: FooBar/class Here, the VM looks for a file “FooBar in a folder called “class” Also, some might argue that javadoc and doclets are types of preprocessors.

  48. Methods, Control Structures and Data Structures

  49. Java Methods • There exists a single construct, the method, for both procedures and functions: • when a procedure is called for, specify the return type “void” before method name public void printHelloWorld( ) { System.out.println(“Hello World!”); } // of printHelloWorld • Note: All methods must have parentheses for parameters . . . even if no parameters!

  50. Java Methods • Single construct for both procedures and functions: • when a function is called for, specify the • appropriate return type before method name public float average (float fNum1, float fNum2, float fNum3) { float fReturnVal; fReturnVal = (fNum1 + fNum2 + fNum3)/ 3; return (fReturnVal); } // of average

More Related