Advanced Programming Rabie A. Ramadan vPro/ Lecture 1.

Slides:



Advertisements
Similar presentations
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Advertisements

Lab Information Security Using Java (Review) Lab#0 Omaima Al-Matrafi.
Cmp Sci 187: Introduction to Java Based on Appendix A of text (Koffmann and Wolfgang)
Advanced Programming Rabie A. Ramadan vpro/ Lecture 1.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Lab#1 (14/3/1431h) Introduction To java programming cs425
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
Review Java.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Programming Languages and Paradigms Object-Oriented Programming.
Java and C++, The Difference An introduction Unit - 00.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Why Java? A brief introduction to Java and its features Prepared by Mithat Konar.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Chapter 1: Introducing JAVA. 2 Introduction Why JAVA Applets and Server Side Programming Very rich GUI libraries Portability (machine independence) A.
The Java Programming Language
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Effective Java: Creating and Destroying Objects Last Updated: Fall 2012.
Introduction to Computer Systems and the Java Programming Language.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Copyright Curt Hill Variables What are they? Why do we need them?
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Today… “Hello World” ritual. Brief History of Java & How Java Works. Introduction to Java class structure. But first, next slide shows Java is No. 1 programming.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
RealTimeSystems Lab Jong-Koo, Lim
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
JAVA MULTIPLE CHOICE QUESTION.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Effective Java: Creating and Destroying Objects
Internet and Java Foundations, Programming and Practice
Programming Language Concepts (CIS 635)
Focus of the Course Object-Oriented Software Development
Effective Java: 3rd Edition Creating and Destroying Objects
Java Programming Language
Effective Java: Creating and Destroying Objects
Introduction to Java By Prakash G Asnani
Presentation transcript:

Advanced Programming Rabie A. Ramadan vPro/ Lecture 1

2 Welcome Back

Class Organization 3 Attendance is very important Assignments Projects Quizzes

Textbooks 4

Topics to be Covered 5 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

Class Format 6 Some presentations by myself Presentations by you Report discussion biweekly Labs

Grading 7 Midterm grades will be added towards the project Labs Assignments

Agenda 8 Introduction and Course Motivation Project Assignment 1 – Get your hands dirty

Introduction and Course Motivation 9 Computer Programming is the art of making a computer do what you want it to do.

Terminology 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

Key Principles For Using Any Language 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

Performance 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

Who are You ? 13 Just a coder Most of us are coders not programmers Programmer / Developer Writes an efficient code

Project 14 Project

Assignment 1 15 Available on the website

Some Salient Characteristics of Java 16 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

Java Processing and Execution Appendix A: Introduction to Java 17 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

Compiling and Executing a Java Program Appendix A: Introduction to Java 18

Java: Write Once, Run Anywhere Consequence of Java’s history: platform- independence Mac user running Safari Windows user running Internet Explorer Web page stored on Unix server Click on link to Applet Byte code is downloaded Virtual machine translates byte code to native Mac code and the Applet is run Byte code (part of web page)

Java: Write Once, Run Anywhere Consequence of Java’s history: platform-independent Mac user running Safari Windows user running Internet Explorer Web page stored on Unix server Click on link to AppletByte code is downloaded Virtual machine translates byte code to native Windows code and the Applet is run

Java: Write Once, Run Anywhere (2) But Java can also create standard (non- web based) programs Dungeon Master (Java version) Examples of mobile Java games: Kung Fu Panda 2: THQ

Java: Write Once, Run Anywhere (3) Java has been used by large and reputable companies to create serious stand-alone applications. Example: Eclipse 1 : started as a programming environment created by IBM for developing Java programs. The program Eclipse was itself written in Java. 1 For more information:

Compiled Programs With Different Operating Systems Windows compiler Executable (Windows) UNIX compiler Executable (UNIX) Mac OS compiler Executable (Mac) Computer program

A High Level View Of Translating/Executing Java Programs Java compiler (javac) Java program Filename.java Java bytecode (generic binary) Filename.class Stage 1: Compilation

A High Level View Of Translating/Executing Java Programs (2) Java interpreter (java) Java bytecode (generic binary) Filename.class Machine language instruction (UNIX) Machine language instruction (Windows) Machine language instruction (Apple) Stage 2: Interpreting and executing the byte code

Classes and Objects Appendix A: Introduction to Java 26 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

Grouping Classes: The Java API 27 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)

A Little Example of import and main 28 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

Processing and Running HelloWorld 29 javac HelloWorld.java Produces HelloWorld.class (byte code) java HelloWorld Starts the JVM and runs the main method

References and Primitive Data Types 30 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

Primitive Data Types 31 Represent numbers, characters, boolean values Integers: byte, short, int, and long Real numbers: float and double Characters: char

Primitive Data Types Data typeRange of values byte (8 bits) short -32, ,767 (16 bits) int -2,147,483, ,147,483,647 (32 bits) long -9,223,372,036,854,775, (64 bits) float +/ to +/ and 0, about 6 digits precision double +/ to +/ and 0, about 15 digits precision char Unicode characters (generally 16 bits per char) boolean True or false 32

Operators subscript [ ], call ( ), member access. 2. pre/post-increment ++ --, boolean complement !, bitwise complement ~, unary + -, type cast (type), object creation new 3. * / % 4. binary + - ( + also concatenates strings) 5. signed shift >, unsigned shift >>> 6. comparison >=, class test instanceof 7. equality comparison == != 8. bitwise and & 9. bitwise or |

Operators logical (sequential) and && 12. logical (sequential) or || 13. conditional cond ? true-expr : false-expr 14. assignment =, compound assignment += -= *= /= >= >>>= &= |=

Type Compatibility and Conversion 35 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 byte to short to int to long int kind to float to double

Declaring and Setting Variables 36 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)

Java Control Statements 37 A group of statements executed in order is written { stmt1; stmt2;...; stmtN; } The statements execute in the order 1, 2,..., N

Java Control Statements (continued) Appendix A: Introduction to Java 38

Java Control Statements (continued) 39

Methods 40 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 object is passed Change to reference variable does not affect caller But operations can affect the object, visible to caller

The String Class Appendix A: Introduction to Java 41 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

Comparing Objects 42 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!)

The StringBuffer Class Appendix A: Introduction to Java 43 Stores character sequences Unlike a String object, you can change the contents of a StringBuffer object

StringTokenizer Class 44 We often need to process individual pieces, or tokens, of a String

Arrays 45 In Java, an array is also an object The elements are indexes and are referenced using the form arrayvar[subscript]

Array Example 46 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 Variations 47 // 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; }

Input/Output using Streams 48 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

Opening and Using Files: Reading Input 49 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) {... }

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.

Item 1: Consider Static Factory Methods Instead of Constructors Constructor Calls vs Static Factory Method

Item 1: Advantages Unlike constructors, static factory methods Can have meaningful names Need not create new instances Can return any subtype of return type Reduces client dependency on specific class Can reduce verbosity of creating parameterized type instances

Advantage 2: Not Required To Create New Object Instance-controlled classes can be useful Can avoid creating unnecessary duplicate objects Boolean.valueOf(boolean) is an example Can guarantee a “singleton” or “noninstatiable” object Can allow for very fast “equals” test

Advantage 3: Can Return Subtype of Return Type Consider the java.util.Collections classjava.util.Collections 32 Convenience implementations of Collection interfaces All are static factory methods Interface return type vs. actual classes Static factory methods can hide multiple implementations java.util.EnumSet has two implementations Future release could easily change this Clients neither know nor care about actual type Reduce client dependencies!

Advantage 4: Reduce Verbosity of Parameterized Type Instances // Parameterized type instances Map > m = new HashMap >(); vs. // Static factory alternative public static HashMap newInstance() { return new HashMap (); } // Now, client code looks like this // Compiler does type inference! Map > m = HashMap.newInstance();

Item 1: Disadvantages of Static Factory Methods Naming conventions necessary valueOf – effectively a type converter (also just of ) getInstance – return instance described by parameters newInstance – like getInstance, but guarantees distinct object getType – like getInstance, but converts type newType – like newInstance, but converts type

Item 3: Enforce Singleton Property A Singleton is a class that’s instantiated exactly once Note: singletons are hard to mock in unit testing Two approaches before Enums: Public static member (a constant, of course) Public static factory method Enum singleton is now preferred Lots of subtle advantages: security, serialization, etc.

Item 3: Code Example // Option 1: public final field public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {...} } // Option 2: static factory method public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {...} public static Elvis getInstance() { return INSTANCE; } } // Option 3: Enum type – now the preferred approach public enum Elvis { INSTANCE;... }

Item 4: Enforce Noninstantiability With a Private Constructor Some classes just group static methods and/or fields Makes no sense to instantiate such a class Trying to enforce noninstantiability by making class abstract doesn’t work Subclassing is possible Clients are led to believe subclassing makes sense However, a private constructor does the job

Item 4: Code Example // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { private UtilityClass() { throw new AssertionError(); throw new AssertionError(); }... // Remainder of class omitted } // Note that no subclassing is possible (constructor chaining...) // Note that client can’t call constructor // Note that if constructor is mistakenly called inside class, // there is an immediate assertion violation.

Item 5: Avoid Creating Unnecessary Objects On the one hand, performance is a secondary concern behind correctness On the other, gratuitous object creation is just bad programming  // String s = new String(“stringette”); // Don’t do this! vs. // String s = “stringette”; // Let JVM optimize for you // Also see earlier Boolean.valueOf() static factory example

Item 5: Code Example public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted // DON’T DO THIS public boolean isBabyBoomer() { // Unnecessary allocation of expensive object Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomStart = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomEnd = gmtCal.getTime(); return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0; }

Item 5: Code Example Fixed public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted private static final Date BOOM_START; private static final Date BOOM_END; static { // Note static block Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_START = gmtCal.getTime(); BOOM_START = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_END = gmtCal.getTime(); BOOM_END = gmtCal.getTime(); } public boolean isBabyBoomer() { public boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; birthDate.compareTo(BOOM_END) < 0; } }

Item 5: Autoboxing Overhead // Hideously slow program! Can you spot the object creation? public static void main(String[] args) { Long sum = 0L; for (long i =0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); } // Lessons: 1) prefer primitives to Boxed primitives // 2) watch for unintentional autoboxing // why are you using classes where there is no need for them?

Item 6: Eliminate Obsolete Object References Sometimes, you manage your own memory (leak) Example: Stack.javaStack.java public Object pop () { if (size == 0) throw new IllegalStateException("Stack.pop"); Object result = elements[--size]; elements[size] = null; // Eliminate obsolete reference return result; } Also a problem with caches and registration of listeners and callbacks Suggestion: Use weak pointers, such as WeakHashMap

Item 7: Avoid Finalizers finalize() is a method in the Object class What the garbage collector may call when cleaning up an unused object Finalizers: unpredictable, dangerous, unnecessary! They are NOT the analog of C++ destructors There is no guarantee a finalizer will ever be called Finalizers have severe performance penalties Instead, provide explicit termination methods Sometimes requires “finalizer chaining”

Item 7: Code Example // try-finally block guarantees execution of termination method // termination method ensures resources are released // Example resources: database connections, threads, windows Foo foo = new Foo(); try { // Do what must be done with foo } finally { foo.terminate(); // Explicit termination method in Foo }

Item 7: Finalizer chaining // Manual finalizer chaining // Only do this if you *have* to use the protected void finalize() throws Throwable { try {... // Finalize subclass state } finally super.finalize(); // Note order of finalizer chaining }