870 likes | 1.38k Views
Advanced Programming. Rabie A. Ramadan rabieramadan@gmail.com http://www.rabieramadan.org/classes/2014/AdvPro/ Lecture 1. Welcome Back. Attendance is very important Assignments Projects Quizzes. Class Organization. Textbooks. Object Serialization Advanced I/O - New I/O Reflection
E N D
Advanced Programming Rabie A. Ramadan rabieramadan@gmail.com http://www.rabieramadan.org/classes/2014/AdvPro/ Lecture 1
Attendance is very important Assignments Projects Quizzes Class Organization
Object Serialization Advanced I/O - New I/O Reflection Advanced JDBC Networking with Sockets Remote Method Invocation Keys, Signatures, and Certificates Java Authentication and Authorization Service (JAAS) Parsing XML with Java - JAXP Java Design Patterns Effective Java topics Topics to be Covered
Some presentations by myself Presentations by you Report discussion biweekly Labs Class Format
Midterm grades will be added towards the project Labs Assignments Grading
Introduction and Course Motivation Project Assignment 1 – Get your hands dirty Agenda
Computer Programming is the art of making a computer do what you want it to do. Introduction and Course Motivation
API – Application Programming Interface Classes, Interfaces, Constructors, Members, and Serialized Forms By Which a Programmer Accesses a Class, Interface, or Package User A Programmer Who Writes a Program That Uses an API Client A Class Whose Implementation Uses an API Terminology
Focus on Clarity and Simplicity Don’t Surprise Users of an API Hide Complexity Underneath, Not In, The API Reuse Rather Than Copy Minimize Dependencies Between Modules Some Early Habits Need to Be Broken Detect Errors As Soon As Possible Compile-Time Detection Beats Run-Time Failure Run-Time Exceptions Beat Undefined Behavior Key Principles For Using Any Language
Bloch Does not Focus on Performance Instead, Strive to Write Programs that are: Clear, Correct, Robust, Flexible, Maintainable Start With Sound Software Engineering Get Performance Later Where You Need It Excessive Performance Focus Has Real Costs Think About Why a Language Like C++ is so Complex Performance
Just a coder Most of us are coders not programmers Programmer / Developer Writes an efficient code Who are You ?
Project Project
Available on the website Assignment 1
Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented: Structured in terms of classes, which group data with operations on that data Can construct new classes by extending existing ones Java designed as A core language plus A rich collection of commonly available packages Java can be embedded in Web pages Some Salient Characteristics of Java
Begin with Java source code in text files: Model.java A Java source code compiler produces Java byte code Outputs one file per class:Model.class May be standalone or part of an IDE A Java Virtual Machine loads and executes class files May compile them to native code (e.g., x86) internally Java Processing and Execution Appendix A: Introduction to Java
Compiling and Executing a Java Program Appendix A: Introduction to Java
Click on link to Applet Byte code is downloaded Java: Write Once, Run Anywhere • Consequence of Java’s history: platform-independence Mac user running Safari Web page stored on Unix server Virtual machine translates byte code to native Mac code and the Applet is run Windows user running Internet Explorer Byte code (part of web page)
Click on link to Applet Byte code is downloaded Java: Write Once, Run Anywhere • Consequence of Java’s history: platform-independent Mac user running Safari Web page stored on Unix server Windows user running Internet Explorer Virtual machine translates byte code to native Windows code and the Applet is run
Dungeon Master (Java version) http://homepage.mac.com/aberfield/dmj/ Kung Fu Panda 2: THQ Java: Write Once, Run Anywhere (2) • But Java can also create standard (non-web based) programs Examples of mobile Java games: http://www.mobilegamesarena.net
Java: Write Once, Run Anywhere (3) • Java has been used by large and reputable companies to create serious stand-alone applications. • Example: • Eclipse1: started as a programming environment created by IBM for developing Java programs. The program Eclipse was itself written in Java. 1 For more information: http://www.eclipse.org/downloads/
Compiled Programs With Different Operating Systems UNIX compiler Executable (UNIX) Windows compiler Executable (Windows) Computer program Mac OS compiler Executable (Mac)
Filename.java Filename.class Java compiler (javac) Java program Java bytecode (generic binary) A High Level View Of Translating/Executing Java Programs Stage 1: Compilation
Machine language instruction (UNIX) Filename.class Java interpreter (java) Machine language instruction (Windows) Java bytecode (generic binary) Machine language instruction (Apple) A High Level View Of Translating/Executing Java Programs (2) Stage 2: Interpreting and executing the byte code
The class is the unit of programming A Java program is a collection of classes Each class definition (usually) in its own .java file The file name must match the class name A class describes objects (instances) Describes their common characteristics: is a blueprint Thus all the instances have these same characteristics These characteristics are: Data fields for each object Methods (operations) that do work on the objects Classes and Objects Appendix A: Introduction to Java
API = Application Programming Interface Java = small core + extensive collection of packages A package consists of some related Java classes: Swing: a GUI (graphical user interface) package AWT: Application Window Toolkit (more GUI) util: utility data structures The import statement tells the compiler to make available classes and methods of another package A main method indicates where to begin executing a class (if it is designed to be run as a program) Grouping Classes: The Java API
import javax.swing.*; // all classes from javax.swing public class HelloWorld { // starts a class public static void main (String[] args) { // starts a main method // in: array of String; out: none (void) } } public = can be seen from any package static = not “part of” an object ALittle Example of import and main
javac HelloWorld.java Produces HelloWorld.class (byte code) javaHelloWorld Starts the JVM and runs the main method Processing and Running HelloWorld
Java distinguishes two kinds of entities Primitive types Objects Primitive-type data is stored in primitive-type variables Reference variables store the address of an object References and Primitive Data Types
Represent numbers, characters, boolean values Integers: byte, short, int, and long Real numbers: float and double Characters: char Primitive Data Types
subscript [ ], call ( ), member access . pre/post-increment ++ --, boolean complement !, bitwise complement ~, unary + -, type cast (type), object creation new * / % binary + - (+ also concatenates strings) signed shift << >>, unsigned shift >>> comparison < <= > >=, class test instanceof equality comparison == != bitwise and & bitwise or| Operators
logical (sequential) and && logical (sequential) or || conditional cond ? true-expr : false-expr assignment=, compound assignment += -= *= /= <<= >>= >>>= &= |= Operators
Widening conversion: In operations on mixed-type operands, the numeric type of the smaller range is converted to the numeric type of the larger range In an assignment, a numeric type of smaller range can be assigned to a numeric type of larger range bytetoshorttointtolong intkind tofloattodouble Type Compatibility and Conversion
int square; square = n * n; double cube = n * (double)square; Can generally declare local variables where they are initialized All variables get a safe initial value anyway (zero/null) Declaring and Setting Variables
A group of statements executed in order is written { stmt1; stmt2; ...; stmtN; } The statements execute in the order 1, 2, ..., N Java Control Statements
Java Control Statements (continued) Appendix A: Introduction to Java
A Java method defines a group of statements as performing a particular operation static indicates a static or class method A method that is not static is an instance method All method arguments are call-by-value Primitive type: value is passed to the method Method may modify local copy but will not affect caller’s value Object reference: address of objectis passed Change to reference variable does not affect caller But operations can affect the object, visible to caller Methods
The String class defines a data type that is used to store a sequence of characters You cannot modify a String object If you attempt to do so, Java will create a new object that contains the modified character sequence TheStringClass Appendix A: Introduction to Java
You can’t use the relational or equality operators to compare the values stored in strings (or other objects) (You will compare the pointers, not the objects!) ComparingObjects
Stores character sequences Unlike a String object, you can change the contents of a StringBuffer object TheStringBufferClass Appendix A: Introduction to Java
We often need to process individual pieces, or tokens, of a String StringTokenizerClass
In Java, an array is also an object The elements are indexes and are referenced using the form arrayvar[subscript] Arrays
float grades[] = new float[numStudents]; ... grades[student] = something; ... float total = 0.0; for (int i = 0; i < grades.length; ++i) { total += grades[i]; } System.out.printf(“Average = %6.2f%n”, total / numStudents); Array Example
// possibly more efficient for (int i = grades.length; --i >= 0; ) { total += grades[i]; } // uses Java 5.0 “for each” looping for (float grade : grades) { total += grade; } Array Example Variations
An InputStream is a sequence of characters representing program input data An OutputStream is a sequence of characters representing program output The console keyboard stream is System.in The console window is associated with System.out Input/Output using Streams
import java.io.*; public static void main (String[] args) { // open an input stream (**exceptions!) BufferedReader rdr = new BufferedReader( new FileReader(args[0])); // read a line of input String line = rdr.readLine(); // see if at end of file if (line == null) { ... } Opening and Using Files: Reading Input
Item 1: Consider Static Factory Methods Instead of Constructors • Factory methods: • Have names, unlike constructors, which can clarify code. • Do not need to create a new object upon each invocation - objects can be cached and reused, if necessary. • Can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller.