Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 Course Objectives 2 Basic programming concepts in Java language Object-oriented approach to software design and development Java APIs including Java Collection API Graphical User Interface packages Database connectivity (JDBC) Web application (applet) Design and implement medium-size standalone and web applications Assume some knowledge of C++ or C programming Reference textbook 3 Thnking in Java, Bruce Eckel, Free Electronic Version Great for someone with C/C++ programming experience Java How to Program, H.M. Deitel and P.J. Deitel, 8th Edition, Prentice Hall, late object version For beginner programmers We take late object approach i.e., we first focus on basic programming constructs Focus and philosophy 4 Software reuse: building-block approach to create programs. Avoid reinventing the wheel—use existing pieces wherever possible. Building blocks: classes from class libraries, classes you wrote before, and classes that others create and make available to you (many are available over Internet for free) Focus and philosophy (2) 5 Benefits of software reuse: save program development time often improve program performance (as libraries carefully written to perform efficiently) To use building blocks Read documentation for the version of Java Refer to it frequently to be sure you are aware of the rich collection of Java features and are using them correctly. When in doubt, experiment and see what happens. Online resource 6 • • http://www.oracle.com/technetwork/java/index.ht ml : official info. about Java including documentation, software, announcements, tutorials, and much more. In particular, class library documentation at http://download.oracle.com/javase/1.4.2/docs/api/ • Download a zip or tar file and install it on your own PC. History of Java 7 Originally for intelligent consumer-electronic devices in Sun Microsystems (1990) Reason: C++ not a good fit: Demanded too large a footprint Its complexity led to developer errors No garbage collection, programmers managing system memory => challenging and error-prone Lack of portable support for security, distributed programming, and threading Could not be easily ported to all types of devices Now: large-scale enterprise applications, Web program, consumer devices (cell phones, etc.) Memory footprint 8 Memory footprint: the amount of main memory that a program uses or references while running. Includes code, static data sections (both initialized and uninitialized), heap, stacks structures introduced by run-time environment (compiler, interpreter, Java Virtual Machine): such as symbol tables, constant tables, debugging structures, open files Those that program ever needs while executing and will be loaded at least once during entire run. Java as a platform 9 • • Java is a platform for application development Typically, a platform means some combination of hardware and system software that will mostly run all same software. – – • e.g., PowerMacs running Mac OS 9.2 e.g., DEC Alphas running Windows NT Problem: – Programs very closely tied to specific hardware and operating system they run. – – Program needs to be ported to different platforms Distributing executable programs from web pages is hard Platform Independence of Java 10 • • Java: write one, run everywhere Java compiler (javac) produces byte code • Byte code written in hexadecimal, byte by byte, looks like this: • • • CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08 … Byte code is exactly the same on every platform Interpreter/Just-in-time compiler (java) translates byte code to machine’s native language to execute • Compiler is not platform independent Platform Independence 11 • Only interpreter/JIT compiler and a few native libraries need to be ported to get Java to run on a new computer or operating system • • The rest of the runtime environment, compiler and most of class libraries are written in Java. javac compiler, java interpreter, Java programming language, and more are collectively referred to as Java. The Scope of Java 12 J2SE J2EE J2ME One Java Platform, Multiple Profiles Java Profiles 13 Java Card: allows small Java-based applications to run securely on smart cards and similar smallmemory-footprint devices Smart card, chip card, or integrated circuit card, is any pocket-sized card with embedded integrated circuits, for providing identification, authentication, data storage and application processing Java ME (Micro Edition): for devices which are sufficiently limited Supplying full set of Java libraries would take up unacceptably large amounts of storage. Java Profiles (cont’d) 14 Java SE (Standard Edition): For general-purpose use on desktop PCs, servers and similar devices. Java EE (Enterprise Edition): Java SE plus various APIs useful for multi-tier client–server enterprise applications 15 Life-cycle of Java Program javac welcome1.java java welcome1 16 17 Introduction to Java Programming 18 We demonstrate how to: Display messages Obtain information from the user Arithmetic calculations Decision-making fundamentals A quick start, and Illustrates several important Java language features 1 // Fig. 2.1: Welcome1.java 2 // Text-printing program. 19 3 4 public class Welcome1 5 { 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome to Java Programming!" ); 10 11 } // end method main 12 13 } // end clazss Welcome1 Welcome to Java Programming! Line numbers not part of program, added for reference First Program in Java: Printing a Line of Text (Cont.) 20 1 // Fig. 2.1: Welcome1.java 2 // Text-printing program. Comments start with: // Comments ignored during program execution Document and describe code Provides code readability Traditional comments: begin with /*,end with */ /* This is a traditional comment. It can be split over many lines */ No space between / and * Good Programming Practice 21 Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program was last modified. Class declaration 22 3 Blank line 4 Makes program more readable Blank lines, spaces, and tabs are white-space characters Ignored by compiler public class Welcome1 Begins class declaration for class Welcome1 Every Java program has at least one user-defined class Keyword: words reserved for use by the language (here, Java) class keyword must be followed by class name Naming classes: capitalize every word, i.e., camel case SampleClassName Java programmers know that such identifiers normally represent Java classes, so naming your classes in this manner makes your programs more readable. Syntax Error 23 The syntax of a programming language specifies rules for creating a proper program in that language. A syntax error occurs when the compiler encounters code that violates Java’s language rules (i.e., its syntax). E.g., keyword class not followed by an identifier a syntax error When it happens, compiler does not generate .class file. Instead, it issues an error message to help programmer identify and fix incorrect code. also called compiler errors, compile-time errors or compilation errors, because compiler detects them during compilation phase. Rules for identifier 24 4 public class Welcome1 Welcome1 is an example of identifier, name for variable, class or method Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ ) Does not begin with a digit, has no spaces Examples: Welcome1, $value, _value, button7 7button Java a1 is invalid is case sensitive (capitalization matters) and A1 are different Class declaration (2) 25 public class Welcome1 4 Important rules: The above code must be saved as file Welcome1.java, i.e., class name with .java extension Different from C++ 5 { Left brace { Begins body of every class Right brace ends declarations (line 13) It is an error not to end a file name with .java extension for a file containing a class declaration. Good Programming Practice 26 Whenever you type an opening left brace, {, in your program immediately type the closing right brace, }, then reposition the cursor between the braces indent the entire body of class declaration i.e., begin lines with the body by a fixed number of spaces, or a tab Prevent missing or unmatching braces, a syntax error Indentation emphasizes class declaration's structure and makes it easier to read. 27 Good Programming Practice: indentation Set a convention for indent size you prefer Uniformly apply that convention. use Tab key may be used to create indents, but tab stops vary among text editors. use three spaces to form a level of indent. main method 28 public static void main( String args[] ) 7 Part of every Java application Methods can perform tasks and return information void means main returns no information For now, mimic this line in your program { 8 Applications begin executing at main Parentheses indicate main is a method (Ch. 3 and 6) Java applications contain one or more methods Exactly one method must be called main Left brace begins body of method declaration Ended by right brace } (line 11) Good Programming Practice 29 Similar to class declaration, for a method: the body of the method declaration starts with left brace, {, and ends with right brace, } Indent entire body of each method declaration one “level” of indentation Makes structure of codes stand out Statement 30 System.out.println( "Welcome to Java Programming!" ); 9 Statement: instructs computer to perform an action System.out Prints string of characters String - series characters inside double quotes White-spaces in strings are not ignored by compiler Standard output object, usually pointing to command window (i.e., MS-DOS prompt, or PuTTy window) Method System.out.println Displays a line of text Statements Omitting must end with semicolon ; semicolon at end of a statement is a syntax error. Error-Prevention Tip 31 When learning how to program, try “break” a working program to familiarize yourself with compiler's syntax-error messages. E.g. remove a semicolon or brace, see error messages incurred Syntax error messages not always give exact position or problem in the code. Cascading effects … Check reported line first, and then check preceding lines for syntax errors First Program in Java: Printing a Line of Text (Cont.) 32 11 } // end method main Ends 13 method declaration } // end class Welcome1 Ends class declaration Comments are added to keep track of ending braces To improve readability, follow closing right brace (}) of a method body or class declaration with an end-of-line comment indicating the method or class declaration to which the brace belongs. Compile Java program 33 From a command prompt window, go to directory where program is stored Type javac Welcome1.java If no syntax errors, Welcome1.class created Has bytecodes that represent application Possible error messages 34 “bad command or filename,” or “javac: command not found” or “'javac' is not recognized as an internal or external command, operable program or batch file,” your Java software installation was not completed properly E.g. system’s PATH environment variable was not set properly Review J2SE Development Kit installation instructions at java.sun.com/j2se/5.0/install.html Interpret syntax-error messages 35 Each syntax-error messages contains file name and line number where an error is detected. E.g., Welcome1.java:6 refers to Welcome1.java at line 6. Remainder of error message provides information about the syntax error. Common compiler error message 36 “Public class a file called The ClassName must be ClassName.java” defined in file name does not match the name of the public class in the file Execute Your First Java Program 37 From terminal window (e.g., Putty) or command prompt (of Windows), type java Welcome1 Launches Java Virtual Machine JVM loads .class file for class Welcome1 .class JVM extension omitted from command execute the program by calling method main of the class Common error message 38 “Exception in thread "main" java.lang.NoClassDefFoundError: Welcome1,” Your CLASSPATH environment variable has not been set properly. See related slide before 1 // Fig. 2.3: Welcome2.java 2 // Printing a line of text with multiple statements. 39 print vs println 3 4 public class Welcome2 5 { 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" ); 11 12 } // end method main 13 14 } // end class Welcome2 Welcome to Java Programming! System.out.print keeps the cursor on the same line, so System.out.println continues on the same line. Display special characters 40 How to display special characters, such as doublequote, newline, … ? Use escape character which starts with backslash ( \ ) to indicate special character E.g., newline characters (\n) Indicates cursor should be at the beginning of the next line 9 Line System.out.println( "Welcome\nto\nJava\nProgramming!" ); breaks at \n 1 // Fig. 2.4: Welcome3.java 2 // Printing multiple lines of text with a single statement. 3 4 public class Welcome3 5 { 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome\nto\nJava\nProgramming!" ); 10 11 } // end method main 12 13 } // end class Welcome3 Welcome to Java Programming! Notice how a new line is output for each \n escape sequence. Some common escape sequences 42 Escape Description sequence \n Newline. Position the screen cursor at the beginning of the next line. \t \r Horizontal tab. Move the screen cursor to the next tab stop. Carriage return. Position the screen cursor at the beginning of the current line—do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. Backslash. Used to print a backslash character. Double quote. Used to print a double-quote character. For example, System.out.println( "\"in quotes\"" ); displays "in quotes" \\ \" Displaying Text with printf 43 System.out.printf Displays formatted data System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!" ); 9 10 First parameter is format string, a string made up of Fixed text, e.g., \n in above example Format specifier – placeholder for a value, specify the type and format for each subsequent paramters Format specifier %s – placeholder for a string 1 // Fig. 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box. 3 4 public class Welcome4 5 { 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 10 System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!" ); 11 12 } // end method main 13 14 } // end class Welcome4 Welcome to Java Programming! System.out.printf displays formatted data. Good Programming Practice 45 Place a space after each comma (,) in an argument list to make programs more readable. Long statement can be split into multiple lines Indent all subsequent lines of the statement Splitting in the middle of an identifier or a string is a syntax error. Second Java Application: Adding Integers 46 Upcoming program Use Scanner to read two integers from user Use printf to display sum of the two values Use packages 1 // Fig. 2.7: Addition.java 2 // Addition program that displays the sum of two numbers. 3 import java.util.Scanner; // program uses class Scanner import declaration imports class Scanner from package java.util. 4 5 public class Addition 6 { Outline 47 7 // main method begins execution of Java application 8 public static void main( String args[] ) 9 { Declare and initialize (1 variable of 2) input, which is a Scanner. import 10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in ); 12 13 int number1; // first number to add 14 int number2; // second number to add 15 int sum; // sum of number1 and number2 Addition. java declaration Scanner nextInt Declare variables number1, number2 and sum. 16 17 System.out.print( "Enter first integer: " ); // prompt 18 number1 = input.nextInt(); // read first number from user 19 Read an integer from the user and assign it to number1. Outline 48 20 System.out.print( "Enter second integer: " ); // prompt 21 number2 = input.nextInt(); // read second number from Readuser an integer 22 23 24 25 26 27 from the user and assign it to number2. Additi Calculate the sum of the on.jav System.out.printf( "Sum is %d\n", sum ); // display sum variables number1 and a result to number2, assign sum = number1 + number2; // add numbers } // end method main sum. 28 (2 of 2) 4. Addition Display the sum using 5. printf formatted output. 29 } // end class Addition Enter first integer: 45 Enter second integer: 72 Sum is 117 Two integers entered by the user. Second Java Application: Adding Integers (Cont.) 49 3 import java.util.Scanner; import // program uses class Scanner declarations Used by compiler to identify and locate classes used in Java programs Tells compiler to load class Scanner from java.util package 5 6 public class Addition { Begins public class Addition Recall Lines that file name must be Addition.java 8-9: begins main Common Programming Error 50 All import declarations must appear before the first class declaration in the file. Placing an import declaration inside a class declaration’s body or after a class declaration is a syntax error. Forgetting to “import” a class used in your program typically results in compilation error such as “cannot resolve symbol.” Make sure to provide proper import declarations Variable declaration statement 51 10 11 // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); Variables Location in memory that stores a value Declare with name and type before use input is of type Scanner,a class that enables a program to read data from keyboard Variable name: any valid identifier (recall the rule?) Declarations end with semicolons ; Initialize variable in its declaration Equal sign stands for assignment operator The parameter System.in refers to standard input object (often links to keyboard) The input variable will be used to read inputs from keyboard Primitive types 52 int number1; // first number to add int number2; // second number to add int sum; // second number to add 13 14 15 Declare variable number1, number2 and sum of type int int holds integer values (whole numbers): i.e., 0, -4, 97 Types float and double hold decimal numbers Type char holds a single character: i.e., x, $, \n, 7 int, float, double and char are primitive types Comments to describe purpose of variables int number1, // first number to add number2, // second number to add sum; // second number to add Can declare multiple variables of the same type in one declaration Use comma-separated list Good Programming Practice 53 Declare each variable on a separate line allows a descriptive comment to be easily inserted next to each declaration. Choose meaningful variable names self-documenting program Convention for variable-name identifiers begin with a lowercase letter, and every subsequent word in the name begins with a capital letter e.g., firstNumber, studentRecord, … Second Java Application: Adding Integers (Cont.) 54 System.out.print( "Enter first integer: " ); // prompt 17 Message called a prompt - directs user to perform an action 18 number1 = input.nextInt(); // read first number from user Result of call to nextInt given to number1 using assignment operator = Assignment statement = binary operator - takes two operands Expression on right evaluated and assigned to variable on left Read as: number1 gets the value of input.nextInt() 55 Software Engineering Observation 2.1 By default, package java.lang is imported in every Java program; thus, java.lang is the only package in the Java API that does not require an import declaration. Good Programming Practice 56 Place spaces on either side of a binary operator to make it stand out and make the program more readable. Another Java Application: Adding Integers (Cont.) 57 20 System.out.print( "Enter second integer: " ); // prompt Similar to previous statement Prompts 21 number2 = input.nextInt(); // read second number from user Similar to previous statement Assign 23 the user to input the second integer variable number2 to second integer input sum = number1 + number2; // add numbers Assignment Calculates statement sum of number1 and number2 (right hand side) Uses assignment operator = to assign result to variable sum Read as: sum gets the value of number1 + number2 number1 and number2 are operands Another Java Application: Adding Integers (Cont.) 58 System.out.printf( "Sum is %d\n: " , sum ); // display sum 25 Use System.out.printf to display results Format specifier %d Placeholder for an int value System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) ); Calculations can also be performed inside printf Parentheses around the expression number1 + number2 are not required Variables stored in memory 59 Variable has a name, a type, a size and a value Variables are stored in main memory Size of memory depends on the type Name corresponds to location in memory Mapping performed by compiler Assignment statement: place new value into variable, replaces (and destroys) previous value Reading variables from memory does not change them Illustration of variables in memory 60 Arithmetic Expression 61 Arithmetic calculations used in most programs Usage for multiplication / for division % for remainder +, * Integer division truncates remainder 7 / 5 evaluates to 1 Remainder operator % returns the remainder 7 % 5 evaluates to 2 Arithmetic operators 62 Java operation Arithmetic Algebraic operator expression Java expression Addition + f+7 f + 7 Subtraction – p–c p - c Bm b * m Multiplication * Division / x / y or or x ÷ y x / y Exercise: write an expression to convert temperature from Farenheith degree to Celsus degree: Hint: Tf = (9/5)*Tc+32; Tc = temperature in degrees Celsius Tf = temperature in degrees Fahrenheit Operator Precedence 63 Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 Precedence of arithmetic operators 64 Operator(s) Operation(s) Order of evaluation (precedence) * Multiplication / Division % Remainder + Addition - Subtraction Evaluated first. If there are several operators of this type, they are evaluated from left to right. Evaluated next. If there are several operators of this type, they are evaluated from left to right. Good Programming Practice 65 Refer to operator precedence chart when writing expressions containing many operators. Confirm that the operations in the expression are performed in the order you expect. When uncertain, use parentheses to force the order, exactly as you would do in algebraic expressions. Some operators, such as assignment, =, associate from right to left rather than from left to right. Evaluation order of a second-degree polynomial 66 Decision Making: Equality and Relational Operators 67 if statement (Simple version here, more detail later) if (condition) body If the condition is true, then the body of the if statement executed Execute resumes at statement after the if statement Condition: expression that is either true or false can be formed using equality or relational operators Body of the if statement can be: A single statement A block of statement Equality and relational operators 68 Standard algebraic Java equality Sample equality or relational or relational Java operator operator condition Equality operators Relational operators ≤ Meaning of Java condition == != x == y x != y x is equal to y x is not equal to y > < >= <= x x x x x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y > y < y >= y <= y 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Fig. 2.15: Comparison.java // Compare integers using if statements, relational operators // and equality operators. import java.util.Scanner; // program uses class Scanner 69 public class Comparison { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; // first number to compare int number2; // second number to compare System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user if ( number1 == number2 ) System.out.printf( "%d == %d\n", number1, number2 ); Test for equality, display result using printf. if ( number1 != number2 ) System.out.printf( "%d != %d\n", number1, number2 ); if ( number1 < number2 ) System.out.printf( "%d < %d\n", number1, number2 ); Compares two numbers using relational operator <. 31 32 33 if ( number1 > number2 ) System.out.printf( "%d > %d\n", number1, number2 ); 34 35 36 if ( number1 <= number2 ) System.out.printf( "%d <= %d\n", number1, number2 ); 37 38 39 if ( number1 >= number2 ) System.out.printf( "%d >= %d\n", number1, number2 ); 40 41 } // end method main 42 43 } // end class Comparison Enter first integer: 777 Enter second integer: 777 777 == 777 777 <= 777 777 >= 777 Enter first integer: 1000 Enter second integer: 2000 1000 != 2000 1000 < 2000 1000 <= 2000 Enter first integer: 2000 Enter second integer: 1000 2000 != 1000 2000 > 1000 2000 >= 1000 70 Compares two numbers using relational operator >, <= and >=. Decision Making: Equality and Relational Operators (Cont.) 71 Line 6: begins class Comparison declaration Line 12: declares Scanner variable input and assigns it a Scanner that inputs data from the standard input Lines 14-15: declare int variables Lines 17-18: prompt the user to enter the first integer and input the value Lines 20-21: prompt the user to enter the second integer and input the value Decision Making: Equality and Relational Operators (Cont.) 72 if ( number1 == number2 ) System.out.printf( "%d == %d\n", number1, number2 ); 23 24 if If statement to test for equality using (==) variables equal (condition true) Line 24 executes If variables not equal, statement skipped Empty statement Lines No task is performed 26-27, 29-30, 32-33, 35-36 and 38-39 Compare number1 and number2 with the operators !=, <, >, <= and >=, respectively Common Programming Error 73 Confusing equality operator, ==, with assignment operator, =, leads to logic error or syntax error. == read as “is equal to” = read as “gets”, or “gets the value of.” It is a syntax error to add spaces between symbols in operators ==, !=, >= and <= Reversing operators !=, >= and <=, as in =!, => and =<, is a syntax error. Placing a semicolon immediately after right parenthesis of condition in an if statement is normally a logic error. Assignments 74 You can choose to set up Java environment on your own computer (Optional) Download and install Eclipse IDE for Java at http://www.eclipse.org/downloads/ Download and install Java Runtime Environment at Use info. at the following page to decide which version to download: http://www.eclipse.org/downloads/moreinfo/jre.php Lab1 assignment Acknowledgement 75 Parts of the slides are adapted from powerpoint s slides for Java How To Program, 1992-2010 by Pearson Education, Inc. All Rights Reserved.