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
Java An Introduction to Software Development Using JAVA Objectives: • Understand the software development process, tools, and priorities • Understand compilers and interpreters • Learn about Java Virtual Machine, bytecodes • Learn to set up and run simple console applications, GUI applications, and applets in Java • Learn basic facts about OOP 2-2 Software Today: 6,460,000,000 2-3 Software Applications • Large business systems • • • • • • Databases Internet, e-mail, etc. Military Embedded systems Scientific research • Word processing and other small business and personal productivity tools • Graphics / arts / digital photography • Games AI 2-4 Software Development 1950-1960's: • Emphasis on efficiency fast algorithms small program size limited memory use Now: • Emphasis on • Often cryptic code • Not user-friendly programmer’s productivity team development reusability of code easier maintenance portability • Better documented • User-friendly 2-5 Programming Languages Assembly languages 1940 1950 C C# LISP Scheme Logo 1960 1970 Fortran Machine code C++ 1980 Pascal Java 1990 2000 Python Basic Smalltalk Smalltalk-80 2-6 Software Development Tools • Editor programmer writes source code • Compiler translates the source into object code (instructions specific to a particular CPU) • Linker converts one or several object modules into an executable program • Debugger steps through the program “in slow motion” and helps find logical mistakes (“bugs”) 2-7 The First “Bug” “(moth) in relay” Mark II Aiken Relay Calculator (Harvard University, 1945) 2-8 Compiled Languages: Edit-Compile-Link-Run Editor Editor Editor Source code Compiler Source code Compiler Source code Compiler Object code Object code Object code Linker Executable program 2-9 Interpreted Languages: Edit-Run Editor Source code Interpreter 2-10 Compiler vs. Interpreter • Compiler: • Interpreter: checks syntax generates machine-code instructions not needed to run the executable program the executable runs faster checks syntax executes appropriate instructions while interpreting the program statements must remain installed while the program is interpreted the interpreted program is slower 2-11 Java’s Hybrid Approach: Compiler + Interpreter • A Java compiler converts Java source code into instructions for the Java Virtual Machine. • These instructions, called bytecodes, are the same for any computer / operating system. • A CPU-specific Java interpreter interprets bytecodes on a particular computer. 2-12 Java’s Compiler + Interpreter Editor Compiler : : 7 K Hello.java Hello.class Interpreter Interpreter : Hello, World! 2-13 Why Bytecodes? • Platform-independent • Load from the Internet faster than source code • Interpreter is faster and smaller than it would be for Java source • Source code is not revealed to end users • Interpreter performs additional security checks, screens out malicious code 2-14 JDK — Java Development Kit • javac • javadoc Java compiler • java Java interpreter • appletviewer tests applets without a browser generates HTML documentation (“docs”) from source • jar packs classes into jar files (packages) All these are command-line tools, no GUI 2-15 JDK (cont’d) • Available free from Sun Microsystems • All documentation is online: http://java.sun.com/javase/index.jsp • Many additional Java resources on the Internet 2-16 Java IDE • GUI front end for JDK • Integrates editor, javac, java, appletviewer, debugger, other tools: specialized Java editor with syntax highlighting, autoindent, tab setting, etc. clicking on a compiler error message takes you to the offending source code line • Usually JDK is installed separately and an IDE is installed on top of it. 2-17 Types of Programs • Console • GUI applications applications • Applets 2-18 Console Applications • Simple text dialog: prompt input, prompt input ... result C:\javamethods\Ch02> path=%PATH%;C:\Program Files\Java\jdk 1.5.0_07\bin C:\javamethods\Ch02> javac Greetings2.java C:\javamethods\Ch02> java Greetings2 Enter your first name: Josephine Enter your last name: Jaworski Hello, Josephine Jaworski Press any key to continue... 2-19 Command-Line Arguments C:\javamethods\Ch02> javac Greetings.java C:\javamethods\Ch02> java Greetings Josephine Jaworski Hello, Josephine Jaworski public class Greetings { public static void main(String[ ] args) { String firstName = args[ 0 ]; String lastName = args[ 1 ]; System.out.println("Hello, " + firstName + " } } Command-line arguments are passed to main as an array of Strings. " + lastName); 2-20 Command-Line Args (cont’d) • Can be used in GUI applications, too • IDEs provide ways to set them (or prompt for them) Josephine Jaworski 2-21 Greetings2.java import java.util.Scanner; public class Greetings2 { public static void main(String[ ] args) { Scanner kboard = new Scanner(System.in); System.out.print("Enter your first name: "); String firstName = kboard.nextLine( ); Prompts System.out.print("Enter your last name: "); String lastName = kboard.nextLine( ); System.out.println("Hello, " + firstName + " " + lastName); System.out.println("Welcome to Java!"); } } 2-22 GUI Applications Menus Clickable panel Buttons Slider 2-23 HelloGui.java import java.awt.*; import javax.swing.*; GUI libraries public class HelloGui extends JFrame { < ... other code > public static void main(String[ ] args) { HelloGui window = new HelloGui( ); // Set this window's location and size: // upper-left corner at 300, 300; width 200, height 100 window.setBounds(300, 300, 200, 100); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } } 2-24 HelloApplet.java import java.awt.*; import javax.swing.*; public class HelloApplet extends JApplet { public void init( ) No main in applets: the init { method is called by JDK’s ... appletviewer or the browser } < ... other code > } 2-25 OOP — Object-Oriented Programming • An OOP program models a world of active objects. • An object may have its own “memory,” which may contain other objects. • An object has a set of methods that can process messages of certain types. 2-26 OOP (cont’d) • A method can change the object’s state, send messages to other objects, and create new objects. • An object belongs to a particular class, and the functionality of each object is determined by its class. • A programmer creates an OOP application by defining classes. 2-27 The Main OOP Concepts: • Inheritance: a subclass extends a superclass; the objects of a subclass inherit features of the superclass and can redefine them or add new features. • Event-driven programs: the program simulates asynchronous handling of events; methods are called automatically in response to events. 2-28 Inheritance • A programmer can define hierarchies of classes • More general classes are closer to the top Person Child Baby Toddler Adult Teen 2-29 OOP Benefits • Facilitates team development • Easier to reuse software components and write reusable software • Easier GUI (Graphical User Interface) and multimedia programming 2-30 Review: • What are some of the current software development concerns? • What are editor, compiler, debugger used for? • How is a compiler different from an interpreter? • Name some of the benefits of Java’s compiler+interpreter approach. • Define IDE. 2-31 Review (cont’d): • • • • What is a console application? What are command-line arguments? What is a GUI application? What is the difference between a GUI application and an applet? • What is OOP? • Define inheritance. 2-32 Introduction • Present the syntax of Java • Introduce the Java API • Demonstrate how to build stand-alone Java programs Java applets, which run within browsers e.g. Netscape • Example programs 2-33 Why Java? • It’s the current “hot” language • It’s entirely object-oriented • It has a vast library of predefined objects and • operations It’s more platform independent this makes it great for Web programming • It’s more secure • It isn’t C++ 2-34 Applets, Servlets and Applications • An applet is designed to be embedded in a • • • Web page, and run by a browser Applets run in a sandbox with numerous restrictions; for example, they can’t read files and then use the network A servlet is designed to be run by a web server An application is a conventional program 2-35 Building Standalone JAVA Programs (on UNIX) • • • • Prepare the file foo.java using an editor Invoke the compiler: javac foo.java This creates foo.class Run the java interpreter: java foo 2-36 Java Virtual Machine • The .class files generated by the compiler are not executable binaries so Java combines compilation and interpretation • Instead, they contain “byte-codes” to be executed by the Java Virtual Machine other languages have done this, e.g. UCSD Pascal • This approach provides platform independence, and greater security 2-37 HelloWorld (standalone) public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } • Note that String is built in • println is a member function for the System.out class 2-38 Comments are almost like C++ • /* This kind of comment can span multiple lines */ • // This kind is to the end of the line • /** * This kind of comment is a special * ‘javadoc’ style comment */ 2-39 Primitive data types are like C • Main data types are int, double, boolean, char • Also have byte, short, long, float • boolean has values true and false • Declarations look like C, for example, double x, y; int count = 0; 2-40 Expressions are like C • Assignment statements mostly look like those in C; you can • • • • • use =, +=, *= etc. Arithmetic uses the familiar + - * / % Java also has ++ and -Java has boolean operators && || ! Java has comparisons < <= == != >= > Java does not have pointers or pointer arithmetic 2-41 Control statements are like C • if (x < y) smaller = x; • if (x < y){ smaller=x;sum += x;} else { smaller = y; sum += y; } • while (x < y) { y = y - x; } • do { y = y - x; } while (x < y) • for (int i = 0; i < max; i++) sum += i; • BUT: conditions must be boolean ! 2-42 Control statements II switch (n + 1) { case 0: m = n - 1; break; case 1: m = n + 1; case 3: m = m * n; break; default: m = -n; break; } • Java also introduces the try statement, about which more later 2-43 Java isn't C! • • • • • In C, almost everything is in functions In Java, almost everything is in classes There is often only one class per file There must be only one public class per file The file name must be the same as the name of that public class, but with a .java extension 2-44 Java program layout • A typical Java file looks like: import java.awt.*; import java.util.*; public class SomethingOrOther { // object definitions go here . . . } This must be in a file named SomethingOrOther.java ! 2-45 What is a class? • Early languages had only arrays all elements had to be of the same type • Then languages introduced structures (called records, or structs) allowed different data types to be grouped • Then Abstract Data Types (ADTs) became popular grouped operations along with the data 2-46 So, what is a class? • A class consists of a collection of fields, or variables, very much like the named fields of a struct all the operations (called methods) that can be performed on those fields can be instantiated • A class describes objects and operations defined on those objects 2-47 Name conventions • Java is case-sensitive; maxval, maxVal, and • • • • • MaxVal are three different names Class names begin with a capital letter All other names begin with a lowercase letter Subsequent words are capitalized: theBigOne Underscores are not used in names These are very strong conventions! 2-48 The class hierarchy • Classes are arranged in a hierarchy • The root, or topmost, class is Object • Every class but Object has at least one superclass • A class may have subclasses • Each class inherits all the fields and methods of its (possibly numerous) superclasses 2-49 An example of a class class Person { String name; int age; void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } } 2-50 Another example of a class class Driver extends Person { long driversLicenseNumber; Date expirationDate; } 2-51 Creating and using an object • Person john; john = new Person ( ); john.name = "John Smith"; john.age = 37; • Person mary = new Person ( ); mary.name = "Mary Brown"; mary.age = 33; mary.birthday ( ); 2-52 An array is an object • Person mary = new Person ( ); • int myArray[ ] = new int[5]; or: • int myArray[ ] = {1, 4, 9, 16, 25}; • String languages [ ] = {"Prolog", "Java"}; 2-53 Objects and Classes 2-54 Objectives: • See an example of a small program written in OOP style and discuss the types of objects used in it • Learn about the general structure of a class, its fields, constructors, and methods • Get a feel for how objects are created and how to call their methods • Learn a little about inheritance in OOP 2-55 OOP • An OO program models the application as a world of interacting objects. • An object can create other objects. • An object can call another object’s (and its own) methods (that is, “send messages”). • An object has data fields, which hold values that can change while the program is running. 2-56 Objects • Can model real-world objects • Can represent GUI (Graphical User Interface) components • Can represent software entities (events, files, images, etc.) • Can represent abstract concepts (for example, rules of a game, a particular type of dance, etc.) 2-57 Classes and Objects • A class is a piece of the program’s source code that describes a particular type of objects. OO programmers write class definitions. • An object is called an instance of a class. A program can create and use more than one object (instance) of the same class. 2-58 Class Object • A blueprint for objects of a particular type Attributes • Defines the structure (number, types) of the attributes Behaviors • Defines available behaviors of its objects 2-59 Class: Car Attributes: String model Color color int numPassengers double amountOfGas Object: a car Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5 Behaviors: Behaviors: Add/remove a passenger Get the tank filled Report when out of gas 2-60 Class • A piece of the program’s source code • Written by a programmer vs. Object • An entity in a running program • Created when the program is running (by the main method or a constructor or another method) 2-61 Class vs. • Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects • Specifies the possible behaviors of its objects Object • Holds specific values of attributes; these values can change while the program is running • Behaves appropriately when called upon 2-62 Classes and Source Files • Each class is stored in a separate file • The name of the file must be the same as the name of the class, with the extension .java Car.java public class Car { ... } By convention, the name of a class (and its source file) always starts with a capital letter. (In Java, all names are case-sensitive.) 2-63 Libraries • Java programs are usually not written from scratch. • There are hundreds of library classes for all occasions. • Library classes are organized into packages. For example: java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — GUI development package 2-64 import • Full library class names include the package name. For example: java.awt.Color javax.swing.JButton • import statements at the top of the source file let you refer to library classes by their short names: Fully-qualified import javax.swing.JButton; name ... JButton go = new JButton("Go"); 2-65 import (cont’d) • You can import names for all the classes in a package by using a wildcard .*: import java.awt.*; import java.awt.event.*; import javax.swing.*; Imports all classes from awt, awt.event, and swing packages • java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes. 2-66 SomeClass.java import ... import statements public class SomeClass { • Fields • Constructors • Methods } Class header Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects Procedures for constructing a new object of this class and initializing its fields Actions that an object of this class can take (behaviors) 2-67 public class Foot { private Image picture; private CoordinateSystem coordinates; public Foot (int x, int y, Image pic) { picture = pic; coordinates = new CoordinateSystem (x, y, pic); } public void moveForward (int distance) { coordinates.shift (distance, 0); } Fields Constructor Methods public void moveSideways (int distance) { coordinates.shift (0, distance); } ... } 2-68 Fields • A.k.a. instance variables • Constitute “private memory” of an object • Each field has a data type (int, double, String, Image, Foot, etc.) • Each field has a name given by the programmer 2-69 Fields (cont’d) You name it! private [static] [final] datatype name; Usually private May be present: means the field is shared by all objects in the class int, double, etc., or an object: String, Image, Foot May be present: means the field is a constant private Foot leftFoot; 2-70 Constructors • Short procedures for creating objects of a class • • • • Always have the same name as the class Initialize the object’s fields May take parameters A class may have several constructors that differ in the number and/or types of their parameters 2-71 Constructors (cont’d) The name of a constructor is always the same as the name of the class public class Foot { private Image picture; private CoordinateSystem coordinates; public Foot (int x, int y, Image pic) { A constructor can take parameters picture = pic; coordinates = new CoordinateSystem(x, y, pic); } ... } Initializes fields 2-72 Constructors (cont’d) // FootTest.java ... An object is created with Image leftShoe = ...; the new operator ... Foot leftFoot = new Foot (5, 20, leftShoe); ... public class Foot { ... public Foot (int x, int y, Image pic) { ... } ... The number, order, and types of parameters must match Constructor } 2-73 Constructors (cont’d) JButton go = new JButton("Go"); 2-74 Methods • Call them for a particular object: leftFoot.moveForward(20); amy.nextStep( ); ben.nextStep( ); go.setText("Stop"); 2-75 Methods (cont’d) • The number and types of parameters (a.k.a. arguments) passed to a method must match method’s parameters: public void drawString ( String msg, int x, int y ) { ... } g.drawString ("Welcome", 120, 50); 2-76 Methods (cont’d) • A method can return a value to the caller • The keyword void in the method’s header indicates that the method does not return any value public void moveSideways(int distance) { ... } 2-77 Encapsulation and Information Hiding • A class interacts with other classes only through constructors and public methods • Other classes do not need to know the mechanics (implementation details) of a class to use it effectively • Encapsulation facilitates team work and program maintenance (making changes to the code) 2-78 Methods (cont’d) • Constructors and methods can call other public and private methods of the same class. • Constructors and methods can call only public methods of another class. Class X Class Y private field public method public method private method 2-79 Inheritance • In OOP a programmer can create a new class by extending an existing class Superclass (Base class) subclass extends superclass Subclass (Derived class) 2-80 A Subclass... • inherits fields and methods of its superclass • can add new fields and methods • can redefine (override) a method of the superclass • must provide its own constructors, but calls superclass’s constructors • does not have direct access to its superclass’s private fields 2-81 public class Pacer extends Walker { public Pacer (int x, int y, Image leftPic, Image rightPic) { super (x, y, leftPic, rightPic); } Constructor Calls Walker’s constructor using super public void turnAround () { Foot lf = getLeftFoot (); Foot rf = getRightFoot (); lf.turn (180); Calls Walker’s accessor methods rf.turn (180); lf.moveSideways (-PIXELS_PER_INCH * 8); rf.moveSideways (PIXELS_PER_INCH * 8); } A new method } 2-82 public class Walker { ... public int distanceTraveled() { return stepsCount * stepLength; } ... } public class Slowpoke extends Walker { ... public int distanceTraveled() { return super.distanceTraveled ( ) / 10; } ... Calls superclass’s } distanceTraveled method Overrides Walker’s distanceTraveled method 2-83 Objectives: • Discuss primitive data types • Learn how to declare fields and local variables • Learn about arithmetic operators, compound assignment operators, and increment / decrement operators • Discuss common mistakes in arithmetic 2-84 Variables • A variable is a “named container” • that holds a value. q = 100 - q; 5 count means: 1. Read the current value of q 2. Subtract it from 100 3. Move the result back into q mov ax,q mov bx,100 sub bx,ax mov q,bx 2-85 Variables (cont’d) • Variables can be of different data types: int, char, double, boolean, etc. • Variables can hold objects; then the type is the class of the object. • The programmer gives names to variables. • Names of variables usually start with a lowercase letter. 2-86 Variables (cont’d) • A variable must be declared before it can be used: int Type count; double x, y; JButton go; Walker amy; Name(s) String firstName; 2-87 Variables (cont’d) • The assignment operator = sets the variable’s value: count = 5; x = 0; go = new JButton("Go"); firstName = args[0]; 2-88 Variables (cont’d) • A variable can be initialized in its declaration: int count = 5; JButton go = new JButton("Go"); String firstName = args[0]; 2-89 Variables: Scope • Each variable has a scope — the area in the source code where it is “visible.” • If you use a variable outside its scope, the compiler reports a syntax error. • Variables can have the same name when their scopes do not overlap. { int k = ...; ... } for (int k = ...) { ... } 2-90 Fields • Fields are declared outside all constructors and methods. • Fields are usually grouped together, either at the top or at the bottom of the class. • The scope of a field is the whole class. 2-91 Fields (cont’d) Scope public class SomeClass { Fields } Constructors and methods Or: Scope public class SomeClass { Constructors and methods Fields } 2-92 Local Variables • Local variables are declared inside a constructor or a method. • Local variables lose their values and are destroyed once the constructor or the method is exited. • The scope of a local variable is from its declaration down to the closing brace of the block in which it is declared. 2-93 Local Variables (cont’d) public class SomeClass { ... public SomeType SomeMethod (...) { Local variable declared { Scope Local variable declared } } ... } 2-94 Variables (cont’d) • Use local variables whenever appropriate; never use fields where local variables should be used. • Give prominent names to fields, so that they are different from local variables. • Use the same name for local variables that are used in similar ways in different methods (for example, x, y for coordinates, count for a counter, i, k for indices, etc.). 2-95 Variables (cont’d) • Common mistakes: public void someMethod (...) { int x = 0; ... int x = 5; // should be: x = 5; ... Variable declared twice within the same scope — syntax error 2-96 Variables (cont’d) • Common mistakes: private double radius; ... public Circle (...) // constructor { double radius = 5; ... Declares a local variable radius; the value of the field radius remains 0.0 2-97 Primitive Data Types • • • • int double char boolean • • • • byte short long float Used in Java Methods 2-98 Strings • String is not a primitive data type • Strings work like any other objects, with two exceptions: Strings in double quotes are recognized as literal constants + and += concatenate strings (or a string and a number or an object, which is converted into a string) "Catch " + 22 "Catch 22" 2-99 Literal Constants new line tab 'A', '+', '\n', '\t' char -99, 2010, 0 int 0.75, -12.3, 8., .5 double “coin.gif", "1776", "y", "\n" String 2-100 Symbolic Constants • Symbolic constants are initialized final variables: private final int stepLength = 48; private static final int BUFFER_SIZE = 1024; public static final int PIXELS_PER_INCH = 6; 2-101 Why Symbolic Constants? • Easy to change the value throughout the program, if necessary • Easy to change into a variable • More readable, self-documenting code • Additional data type checking by the compiler 2-102 Arithmetic • Operators: +, -, /, * , % • The precedence of operators and parentheses is the same as in algebra • m % n means the remainder when m is divided by n (for example, 17 % 5 is 2; 2 % 8 is 2) % has the same rank as / and * • • Same-rank binary operators are performed in order from left to right 2-103 Arithmetic (cont’d) • The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. • If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int. 2-104 Arithmetic (cont’d) • Caution: if a and b are ints, then a / b is truncated to an int… 17 / 5 gives 3 3 / 4 gives 0 • …even if you assign the result to a double: double ratio = 2 / 3; The double type of the result doesn’t help: ratio still gets the value 0.0. 2-105 Arithmetic (cont’d) • To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; int m = ..., n = ...; double factor = (double)m / (double)n; double factor = (double)m / n; Casts double r2 = n / 2.0; 2-106 Arithmetic (cont’d) • A cast to int can be useful: Returns a double int ptsOnDie = (int)(Math.random() * 6) + 1; int miles = (int)(km * 1.61 + 0.5); Converts kilometers to miles, rounded to the nearest integer 2-107 Arithmetic (cont’d) • Caution: the range for ints is from -231 to 231-1 (about -2·109 to 2·109) • Overflow is not detected by the Java compiler or interpreter: n n n n n n n = = = = = = = 8 9 10 11 12 13 14 10^n 10^n 10^n 10^n 10^n 10^n 10^n = = = = = = = 100000000 1000000000 1410065408 1215752192 -727379968 1316134912 276447232 n! n! n! n! n! n! n! = 40320 = 362880 = 3628800 = 39916800 = 479001600 = 1932053504 = 1278945280 2-108 Arithmetic (cont’d) • Compound assignment operators: • Increment and decrement operators: a = a + b; a = a - b; a += b; a -= b; a = a * b; a *= b; a = a / b; a /= b; a = a % b; a %= b; a = a + 1; a = a - 1; a++; a--; Do not use these in larger expressions 2-109 From Numbers to Strings • The easiest way to convert x into a string is to concatenate x with an empty string: String s = x + ""; Empty string 'A' 123 -1 "A" "123" "-1" .1 3.14 Math.PI "0.1" "3.14" "3.141592653589793" • The same rules apply to System.out.print(x) 2-110 From Objects to Strings • The toString method is called: public class Fraction { private int num, denom; ... public String toString () { return num + "/" + denom; } } Fraction f = new Fraction (2, 3); System.out. println (f) ; Output: 2/3 f.toString() is called automatically 2-111 Review: • What is a variable? • What is the type of a variable that holds an object? • What is meant by the scope of a variable? • What is the scope of a field? • What is the scope of a local variable? 2-112 Review (cont’d): • Is it OK to give the same name to variables in different methods? • Is it OK to give the same name to a field and to a local variable of the same class? • What is the range for ints? • When is a cast to double used? 2-113 Review (cont’d): • Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? • When is a cast to int used? 2-114