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
Introduction to Java Programming Adapted from tutorials by Y. Daniel Liang http://www.cs.armstrong.edu/liang/intro4e/slid e.htm and Mike Scott http://www.cs.utexas.edu/users/scottm/cs307/s chedule.htm A brief history of Java Oak – “Java, whose original name was Oak, was developed as a part of the Green project at Sun. It was started in December '90 by Patrick Naughton, Mike Sheridan and James Gosling and was chartered to spend time (and money!) trying to figure out what would be the "next wave" of computing and how we might catch it. They quickly came to the conclusion that at least one of the waves was going to be the convergence of digitally controlled consumer devices and computers. ” HotJava – The first Java-enabled Web browser (1994) Java, May 23, 1995, Sun World 2 How Java Works Java's platform independence is achieved by the use of the Java Virtual Machine A Java program consists of one or more files with a .java extension When a Java program is compiled the .java files are fed to a compiler which produces a .class file for each class definition The .class file contains Java bytecode. Bytecode is like machine language, but it is intended for the Java Virtual Machine not a specific chip 3 The advantage of Java Java is platform independent – an application written for one computer is very likely to run unchanged on another computer. – “write once, run anywhere” Java is simple – has a simpler syntax than C and C++. – Most of the trickiest and error-prone portions (such as pointer manipulation) of the C languages do not exist in Java. Java is object-oriented – encapsulation, inheritance, and polymorphism – all code must be contained in a class – no free functions (functions that do not belong to some class) like C++ Java is free – can be downloaded free from http://java.sun.com 4 A simple program //This program prints “Hello World!” public class HelloWorld { //main method begins execution of Java //application public static void main(String[] args) { System.out.println("Hello World!"); } } 5 Compile programs On command line – javac file.java A program in Java consists of one or more class definitions, each compiled into its own .class file of Java Virtual Machine object code. One of these classes must define a method main(), which is where the program starts running. 6 Execute Programs On command line – java classname To invoke a Java program, you run the Java interpreter, java, and specify the name of the class that contains the main() method. 7 Set the CLASSPATH The programmer must first set the CLASSPATH environment variable on the computer to tell the Java compiler where to look for the package. For Windows – set CLASSPATH=c:\packages For Unix systems running C shell – setenv CLASSPATH $HOME/packages 8 Preview to Java Language Basic syntax the same as C++ Programmers don’t need to deal with pointers as in C language. All parameters are pass by value. Pass by reference is not possible – no more C++ const & or & Garbage Collection is used – No need for destructors – Not as many memory management issues (memory is still managed, but by the run time system instead of the programmer.) Array index out of bounds causes a runtime error – Java uses the term Exceptions for runtime errors 9 Data Types Primitive Data Types – byte short int long float double boolean char int x; int y = 10; int z, zz; double a = 12.0; boolean done = false, prime = true; char mi = 'D'; – stick with int for integers, double for real numbers Classes and Objects – pre defined or user defined data types consisting of constructors, methods, and fields (constants and fields (variables) which may be primitives or objects.) 10 Java Primitive Data Types Data Type Characteristics Range byte 8 bit signed integer -128 to 127 short 16 bit signed integer -32768 to 32767 int 32 bit signed integer -2,147,483,648 to 2,147,483,648 long 64 bit signed integer -9,223,372,036,854,775,808 to9,223,372,036,854,775,808 float 32 bit floating point number + 1.4E-45 to + 3.4028235E+38 double 64 bit floating point number + 4.9E-324 to + 1.7976931348623157E+308 boolean true or false NA, note Java booleans cannot be converted to or from other types char 16 bit, Unicode Unicode character, \u0000 to \uFFFF 11 Programming advice Be sure that the name of file containing a class is exactly the same as the name of the class being defined. Always begin every program with comments describing the purpose of the program. Use comments liberally throughout the program to explain how each portion of the code works. 12 Naming Conventions Choose meaningful and descriptive names. Variables and method names: – Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea. 13 Naming Conventions, cont. Class names: – Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: – Capitalize all letters in constants. For example, the constant PI. – To improve the consistency and understandability of your code, assign a name to any important constants, and refer to them by that name in the program. 14 Indention in Statement Block Usually indent the statements in a block so that – Easier to identify the block properly & enhance the readability – In all block like function body – Use tab rather space 15 Increment and Decrement Operators int i=10; int newNum = 10*i++; int i=10; int newNum = 10*(++i); Equivalent to Equivalent to int newNum = 10*i; i = i + 1; i = i + 1; int newNum = 10*i; Always keep expressions increment and decrement operators simple and easy to understand. 16 Programming Errors Syntax Errors – Detected by the compiler Runtime Errors – Causes the program to abort Logic Errors – Produces incorrect result 17 Compilation Errors public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i+4); } } 18 Runtime Errors public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / 0; } } Integer division often gives unexpected results. 19 Logic Errors public class ShowLogicErrors { // Determine if a number is between 1 and 100 inclusively public static void main(String[] args) { // Prompt the user to enter a number String input = JOptionPane.showInputDialog(null, "Please enter an integer:", "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE); int number = Integer.parseInt(input); // Display the result System.out.println("The number is between 1 and 100, " + "inclusively? " + ((1 < number) && (number < 100))); System.exit(0); } } 20 Assertions Assertions have the form assert boolean expression : what to output if assertion is false Example if ( (x < 0) || (y < 0) ) { // we know either x or y is assert x < 0 || y < 0 : x + x += y; } else { // we know both x and y are assert x >= 0 && y >= 0 : x y += x; } < 0 " " + y; not less than zero + " " + y; Use assertion liberally in your code – part of style guide 21 Assertions Uncover Errors in Your Logic if ( a < b ) { // we a is less than b assert a < b : a + " " + b; System.out.println(a + " is smaller than " + b); } else { // we know b is less than a assert b < a : a + " " + b; System.out.println(b + " is smaller than " + a); } Use assertions in code that other programmers are going to use. 22 Control Statements Selection Statements –Using if and if...else –Using switch Statements –Conditional Operator Repetition Statements –Looping: while, do-while, and for –Using break and continue if Statement 24 if Statements -- Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); Wrong { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. 25 Note The else clause matches the most recent if clause in the same block. For example, the following statement int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); is equivalent to int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); 26 Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This statement prints B. 27 switch/case Statement Sometimes, it is necessary to test the content of a variable against a list of possible values – Can use a number of if..else if..else – But coding is tedious Java provides a faster and more readable flow of control statement: switch/case The switch structure may be used to select among mutually exclusive options based on the results of a single integer or character expression. 28 switch/case Statement “default” is optional – Recommend to use even just logging – Let you know unexpected value “break” means end of execution for the case – If no, the following will be executed – Recommend to use 29 switch/case vs if/else switch/case can support expression of type: byte, short, char or int – can check the equality for byte, short, char or int – only supports equality checking if/else can support boolean type only – with proper relational operators, can support all primitive type and non-primitive type – can check the equality for long, float, double, boolean and non-primitive types – can use any relational operator. 30 switch/case vs if/else Although switch/case is more restricted, – Its structure is more elegant and easier to read – Faster – Use it whenever possible 31 Looping do/while structure while structure T F T F for structure T F Java’s single-entry/single-exit control structures. 32 Which Loop to Use? The three forms of loop statements, while, do, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. I recommend that you use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition. 33 Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: Wrong for (int i=0; i<10; i++); { System.out.println("i is " + i); } Always use integer variables as for loop indexes, and never modify their values inside the loop. 34 Caution, cont. Similarly, the following loop is also wrong: int i=0; Wrong while (i<10); { System.out.println("i is " + i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; Correct } while (i<10); 35 The break Keyword Continuation condition? false true Statement(s) break Statement(s) Next Statement 36 The continue Keyword Continue condition? false true Statement(s) continue Statement(s) Next Statement 37 Unit 6: Break Vs Continue The break statement, which is used in the switch statement, can be used in the loop body. When the break statement is executed, the program control jumps to the statement after the loop body, i.e. break the loop. The continue statement causes the program control jumps to the end of the loop and then go back to the condition checking and then continues. 38 Unit 6: Break Vs Continue Example: class ContinueAndBreak { public static void main (String args[]) { int num; for (num=1; num<=10; num++) { if (num==5) { break; } System.out.println("num is "+num); } System.out.println("The break makes the system to print the number to 4"); for (num=1; num<=10; num++) { if (num==5) { continue; } System.out.println("num is "+num); } System.out.println("The continue makes the system to skip the number 5"); } 39 } Introducing Methods A method is a collection of statements that are grouped together to perform an operation. Method Structure 40 Introducing Methods, cont. •parameter profile refers to the type, order, and number of the parameters of a method. •method signature is the combination of the method name and the parameter profiles. •The parameters defined in the method header are known as formal parameters. •When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters. 41 Pass-by-value Java programs communicate with their methods using pass-by-value scheme. – prevent a method from accidentally modifying its calling arguments The pass-by-value scheme also applies to objects as well, but the results are different. Passing references to arrays and objects instead of copying the objects themselves is – much more efficient – but weakens the security of the program 42 Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error. 43 Ambiguous Invocation public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } } 44 Class Declaration class Circle { private double radius = 1.0; double findArea(){ return radius * radius * 3.14159; } } 45 Declaring Object Reference Variables ClassName objectReference; Example: Circle myCircle; 46 Creating Objects objectReference = new ClassName(); Example: myCircle = new Circle(); The object reference is assigned to the object reference variable. 47 Differences between variables of primitive Data types and object types Primitive type int i = 1 i 1 Object type Circle c c reference c: Circle Created using new Circle() radius = 1 48 Copying Variables of Primitive Data Types and Object Types Primitive type assignment i=j Object type assignment c1 = c2 Before: After: i 1 i 2 c1 c1 j 2 j 2 c2 c2 Before: After: c1: Circle c2: Circle radius = 5 radius = 9 49 Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer useful. This object is known as garbage. Garbage is automatically collected by JVM. 50 Constructors Circle(double r) { radius = r; Constructors are a } special kind of methods that are Circle() { radius = 1.0; invoked to construct objects. } myCircle = new Circle(5.0); 51 Constructors, cont. A constructor with no parameters is referred to as a default constructor. Constructors must have the same name as the class itself. Constructors do not have a return type—not even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects. 52 Visibility Modifiers By default, the class, variable, or data can be accessed by any class in the same package. public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties. 53 Visibility Modifiers Cont. The instance variables of a class should normally be declared private, and the class methods should be used to provide a standard interface to the class. Use set methods to check the validity and consistency of input data before it is stored in an object’s instance variable. get methods are used to retrieve information from the instance variables and to format it properly for presentation to the outside world. 54 Passing Objects to Methods Passing by value (the value is the reference to the object) 55 Passing Objects to Methods, cont. main method printAreas method times n 5 5 Pass by value (here the value is 5) Reference Pass by value (here the value is the reference for the object) c myCircle Reference myCircle: Circle radius = 1 56 Class Variables, Constants, and Methods Class variables are shared by all the instances of the class. Class methods are not tied to a specific object. Class constants are final variables shared by all the instances of the class. 57 Class Variables, Constants, and Methods, cont. To declare class variables, constants, and methods, use the static modifier. 58 Scope of Variables The scope of instance and class variables is the entire class. They can be declared anywhere inside a class. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. 59 Java API and Core Java classes http://java.sun.com/j2se/1.4.2/docs/api/ java.lang Contains core Java classes, such as numeric classes, strings, and objects. This package is implicitly imported to every Java program. java.awt Contains classes for graphics. java.applet Contains classes for supporting applets. 60 Java API and Core Java classes, cont. java.io Contains classes for input and output streams and files. java.util Contains many utilities, such as date. java.net Contains classes for supporting network communications. 61 Java API and Core Java classes, cont. java.awt.image Contains classes for managing bitmap images. java.awt.peer Platform-specific GUI implementation. Others: java.sql java.rmi 62