Programming in Java Getting Started tsaiwncsie nctu edu

  • Slides: 108
Download presentation
Programming in Java Getting Started 蔡文能 交通大學資訊 程學系 tsaiwn@csie. nctu. edu. tw http: //www.

Programming in Java Getting Started 蔡文能 交通大學資訊 程學系 tsaiwn@csie. nctu. edu. tw http: //www. csie. nctu. edu. tw/~tsaiwn/java/ 交通大學資訊 程學系

Java Getting Started Outline Java History … Java vs. C++ Compilation and Interpretation Java

Java Getting Started Outline Java History … Java vs. C++ Compilation and Interpretation Java Platform Java Applications Java Applets Language Basics Inside the Applets Applications using GUI More about Applets 交通大學資訊 程學系 蔡文能 第 2頁

Java Getting Started Java History December, 1990. - Patrick Naughton started the Green Project

Java Getting Started Java History December, 1990. - Patrick Naughton started the Green Project in Sun. - He recruited James Gosling and Mike Sheridan to help start the project. James Gosling is of emacs fame. (Not James Bond : -) April 1991 - The Green Project (Naughton, Gosling and Sheridan) settled on smart consumer electronics as the delivery platform June 1991 (Gosling想為該語言命名時看到了窗外的一棵橡樹 ) - Gosling started working on the "Oak" compiler (in C), renamed “Java” later. - Naughton, Gosling and Sheridan wrote the runtime-interpreter, also in C Language. August 1991 - Green team demonstrates basic user interface ideas and graphics system to Sun co-founders Scott Mc. Nealy and Bill Joy. 交通大學資訊 程學系 蔡文能 第 3頁

Java Getting Started Interactive TV Summer 1992 - Massive amounts of hacking on Oak,

Java Getting Started Interactive TV Summer 1992 - Massive amounts of hacking on Oak, and related components. October 1992 - Wayne Rosing joined from Sun Labs and assumed management of the team. March 1993 - The team, incorporated as First Person, focused on interactive television after learning about Time Warner's RFP for its interactive cable TV. April 1993 - NCSA Mosaic 1. 0, the first graphical browser for the Internet, was released. June 1993 - Time Warner went with SGI for its interactive cable TV trial, despite acknowledged superiority of Sun technology. 交通大學資訊 程學系 蔡文能 第 4頁

Java Getting Started Change to Internet Summer 1993 - Naughton flew 300, 000 miles

Java Getting Started Change to Internet Summer 1993 - Naughton flew 300, 000 miles selling Oak to anyone involved in consumer electronics and interactive television. - The rate at which people were gaining access to the Internet reaches breakneck speed. April 1994 - Sun Interactive created, half of First. Person employees leave to join it. June 1994 - "Liveoak" project started. Designed by Bill Joy to use Oak for a big small operating system project. July 1994 - Naughton simply retargeted Oak at the Internet after writing a throwaway implementation of a Web browser in a long weekend hack. 交通大學資訊 程學系 蔡文能 第 5頁

Java Getting Started Start Licensing September 1994 - Jonathon Payne and Naughton start writing

Java Getting Started Start Licensing September 1994 - Jonathon Payne and Naughton start writing "Web. Runner, " a Mosaic-like browser later renamed "Hot. Java“. - Hot. Java prototype is first demonstrated to Sun executives. May 1995 - Sun formally announces Java and Hot. Java at Sun. World '95. - Netscape announces its intention to license Java for use in Netscape browser. September 1995 - Sun-sponsored Java development conference held in New York City. - Sunsoft announces suite of business-oriented development products incorporating Java. 交通大學資訊 程學系 蔡文能 第 6頁

Java Getting Started Quick Growth October 1995 - Oracle announces its Web System suite

Java Getting Started Quick Growth October 1995 - Oracle announces its Web System suite of WWW software which includes a Java-compatible browser. - At the Internet World Conference in Boston, many companies announce plans to license Java. Lotus Development Corp. , Intuit Inc. , Borland International Inc. , Macromedia Inc. , Spyglass Inc. December 1995 - Sun and Netscape announced Javascript, a scripting language based on Java. - Sun, Netscape and Silicon Graphics announced new software alliance to develop Internet interactivity tools. - Borland, Mitsubishi Electronics, Sybase and Symatec announced plans to license Java. - IBM and Adobe announce licensing agreement with Sun for use of Java. - Microsoft announces plans to license Java during announcement of suite of new Internet products, including Visual Basic Script. 交通大學資訊 程學系 蔡文能 第 7頁

Java Getting Started Technology Timeline See http: //java. sun. com/features/2000/06/time-line. html A Brief History

Java Getting Started Technology Timeline See http: //java. sun. com/features/2000/06/time-line. html A Brief History of the Green Project by James Gosling - http: //java. sun. com/people/jag/green/index. html The Story of the Java Platform on the java. sun. com Web site - http: //java. sun. com//nav/whatis/storyofjava. html Java: The Inside Story by Michael O'Connell in Sun. World Online - http: //www. sun. com/sunworldonline/swol-07 -1995/swol-07 -java. html The Java Saga by David Bank in Wired - http: //www. wired. com/wired/archive/3. 12/java. saga. html What is Java technology - 1996 - http: //java. sun. com/java 2/whatis/1996/ Java technology: An Early History - 1998 - http: //java. sun. com/features/1998/05/birthday. html 交通大學資訊 程學系 蔡文能 第 8頁

Java Getting Started Sun announced Java on 1995/05/23 交通大學資訊 程學系 蔡文能 第 9頁

Java Getting Started Sun announced Java on 1995/05/23 交通大學資訊 程學系 蔡文能 第 9頁

Java Getting Started JDK – Java development Kit 1995 May JDK 1. 0 1996

Java Getting Started JDK – Java development Kit 1995 May JDK 1. 0 1996 add IDL(Interface Definition Language), RMI (Remote Method Invocation), Java Beans, JDBC (Java Data. Base Connectivity) 1997 JDK 1. 1, add Servlet 1998 November Java 2 (JDK 1. 2) 1999 Oct JDK 1. 3; 2001 JDK 1. 3. 1 2002 JDK 1. 4 2004 JDK 1. 5 (JDK 5. 0) 2006 JDK 6. 0 (JDK 1. 6) 交通大學資訊 程學系 蔡文能 第 15頁

Java Getting Started JDK 1. 0 JDK 1. 1 JDK 1. 2 JDK 1.

Java Getting Started JDK 1. 0 JDK 1. 1 JDK 1. 2 JDK 1. 3 JDK 1. 4 8 packages 212 classes 23 packages 504 classes 59 packages 1520 classes 77 packages 1595 classes 103 packages 131 packages 2175 classes 2656 classes New Events JFC/Swing JNDI Inner class Drag and Drop Java Sound Object Serialization Java 2 D Jar Files International Reflection Timer CORBA Regular Exp Logging Assertions NIO JDK 1. 5 javax. activity, javax. management java. nio, javax. imageio, javax. net, javax. print, javax. security, org. w 3 c javax. naming, javax. sound, javax. transaction JDBC RMI javax. accessibility, javax. swing, org. omg java. math, java. rmi, java. security, java. sql, java. text, java. beans 交通大學資訊 程學系 蔡文能 java. applet, java. awt, java. io, java. lang, java. net, java. util 第 16頁

Java Getting Started Removed Features from C++ pointers --- where the virus is from

Java Getting Started Removed Features from C++ pointers --- where the virus is from operator overloading --- too obscure multiple inheritance --- too problematic preprocessing --- unreadable unions, structs, templates --- unnecessary automatic coercions --- weak on typing destructors --- when to do? goto --- we all know why. C++ C Java == C++--++ 交通大學資訊 程學系 蔡文能 第 17頁

Java == C++--++ Getting Started Added Features Types: (8 primitive types and their class

Java == C++--++ Getting Started Added Features Types: (8 primitive types and their class wrappers) - boolean (1 bit), byte (8 bit signed), char (16 bit, Unicode), - short (16 bit), int (32 bit), long (64 bit), float, double, - String, Array (as object) Multi-level break 從此真的可以不必用 goto (拿掉了) Interfaces 不可多重繼承; 但可implement多個介面 Packages 把相關的 class 集合在同一個子目錄 Automatic garbage collection 不再有 memory leaking Multithread and synchronization Exception handling (做得比 C++ 好) (C只有signal和longjmp) Runtime type checking 交通大學資訊 程學系 蔡文能 第 18頁

Java Getting Started Compilation and Interpretation Compilation - Source code Bytecode My. Program. java

Java Getting Started Compilation and Interpretation Compilation - Source code Bytecode My. Program. java My. Program. class (注意大小寫) Interpretation - Bytecode the machine code instructions for the Java Virtual Machine. the platform-independent codes interpreted by the Java interpreter. 交通大學資訊 程學系 蔡文能 第 19頁

Java Getting Started Write Once, Run Everywhere Other sayings, - Write once, test everywhere.

Java Getting Started Write Once, Run Everywhere Other sayings, - Write once, test everywhere. - Write once, tune everywhere. 交通大學資訊 程學系 蔡文能 第 20頁

Java Getting Started Advantages of Java Platform independent, portable and interoperable Mobile over distributed

Java Getting Started Advantages of Java Platform independent, portable and interoperable Mobile over distributed systems Simple, Object-Oriented C++ Robust and secure Reasonably good performance Interpreted (bytecode) Multithreaded. . . C Java 交通大學資訊 程學系 蔡文能 第 21頁

Java Getting Started How Will Java Change My Life? Java will help you do

Java Getting Started How Will Java Change My Life? Java will help you do the following: - Get started quickly Write less code Write better code Develop programs faster Avoid platform dependencies with 100% Pure Java Write once, Run anywhere Distribute software more easily Well, but better to - Use OOA and OOD to help code - Follow Design Patterns. - Notice the performance problem. E. g. , gaming. 交通大學資訊 程學系 蔡文能 第 22頁

Java Getting Started Java Platform Java Virtual Machine (JVM) Java API - where you

Java Getting Started Java Platform Java Virtual Machine (JVM) Java API - where you need to learn more. API : Application Programming Interface 交通大學資訊 程學系 蔡文能 第 23頁

Java Getting Started Java Editions J 2 EE, J 2 SE, J 2 ME

Java Getting Started Java Editions J 2 EE, J 2 SE, J 2 ME 交通大學資訊 程學系 蔡文能 第 24頁

Java Getting Started Java API The core API gives you the following features: -

Java Getting Started Java API The core API gives you the following features: - The Essentials Applets Networking Internationalization GUI (Graphical User Interface) Security Software components Object serialization …… API : Application Programming Interface 交通大學資訊 程學系 蔡文能 第 25頁

Java Getting Started Of course you can visit home of java: http: //java. sun.

Java Getting Started Of course you can visit home of java: http: //java. sun. com/ 交通大學資訊 程學系 蔡文能 第 26頁

Java Getting Started Of course you can visit home of java: http: //java. sun.

Java Getting Started Of course you can visit home of java: http: //java. sun. com/ 交通大學資訊 程學系 蔡文能 第 27頁

Java Getting Started 要 看 ! Of course you can visit home of java:

Java Getting Started 要 看 ! Of course you can visit home of java: http: //java. sun. com/ 交通大學資訊 程學系 蔡文能 第 28頁

Java Getting Started Types of Java Programs Applications - A standalone program just like

Java Getting Started Types of Java Programs Applications - A standalone program just like a console applications for C/C++. Applets - A plug-in program inside a web page. (runs in a web browser) Servlets - A plug-in program inside a web page but running on server side. JSP (Java Server Page) - An HTML-like text program with Java code. - Similar to ASP and PHP. 交通大學資訊 程學系 蔡文能 第 29頁

Java Getting Started Java Applications (standalone programs) public class name should be same as

Java Getting Started Java Applications (standalone programs) public class name should be same as the name of Java Source File name A Java Application is a standalone program. The source code of Hello. World. App. java: /** * The Hello. World. App class implements an application that * simply displays "Hello World!" to the standard output. */ class Hello. World. App { public static void main(String[] args) { System. out. println("Hello World!"); //Display the string. } } 交通大學資訊 程學系 蔡文能 第 30頁

Java Getting Started The main method public static void main(String[] args) {. . .

Java Getting Started The main method public static void main(String[] args) {. . . } The main Method - Every Java application must contain a main method whose signature looks like this: public static void main(String[] args) - public indicates that the main method can be called by any object. - static indicates that the main method is a class method. - void indicates that the main method does not return any value. Arguments to the main Method - args indicates the strings behind the class name in the command line. - The runtime system passes information to your application through this String array. - For example: java showimage. gif 交通大學資訊 程學系 蔡文能 第 31頁

Java Getting Started Compiling and Run the Application Compiling the source file - Command

Java Getting Started Compiling and Run the Application Compiling the source file - Command line operation > javac Hello. World. App. java - This operation generates Hello. World. class ü Javac is the Java Compiler Run the Application - Command line operation > java Hello. World. App - The argument to the Java interpreter is the name of the class to run, not the name of a file. ü java is the Java Interpreter, also known as JVM(Java Virtual Machine) 交通大學資訊 程學系 蔡文能 第 32頁

Java Getting Started The Annotation Comments in Java Code - /* text */ -

Java Getting Started The Annotation Comments in Java Code - /* text */ - /** documentation */ The JDK javadoc tool uses doc comments when preparing automatically generated documentation. Most JDK manuals are generated by the javadoc tool. - // text 交通大學資訊 程學系 蔡文能 第 33頁

Java Getting Started Javadoc See more in http: //java. sun. com/j 2 se/javadoc/writingdoccomments/index. html

Java Getting Started Javadoc See more in http: //java. sun. com/j 2 se/javadoc/writingdoccomments/index. html /** * Registers the text to display in a tool tip. The text * displays when the cursor lingers over the component. * * @param text The string to display. If the text is null, * the tool tip is turned off for this component. */ public void set. Tool. Tip. Text(String text) { More tags * * * * * @author @version (classes and interfaces only, required) (see footnote 1) @param @return @exception @see @since @serial @deprecated (methods and constructors only) (methods only) (@throws is a synonym added in Javadoc 1. 2) 交通大學資訊 程學系 蔡文能 (or @serial. Field or @serial. Data) (see How and When To Deprecate APIs) 第 34頁

Java Getting Started An Example of Applet A Java Applet runs in web browser.

Java Getting Started An Example of Applet A Java Applet runs in web browser. The source code of Hello. World. java: import java. applet. Applet; import java. awt. Graphics; public class Hello. World extends Applet { public void paint(Graphics g) { g. draw. String("Hello world!", 50, 25); } } 交通大學資訊 程學系 蔡文能 第 35頁

Java Getting Started Run the Applet HTML File that Includes the Applet <HTML> <HEAD><TITLE>A

Java Getting Started Run the Applet HTML File that Includes the Applet <HTML> <HEAD><TITLE>A Simple Program</TITLE></HEAD> <BODY> Here is the output of my program: <APPLET CODE="Hello. World. class" WIDTH=150 HEIGHT=25> </APPLET> </BODY> </HTML> • Run the Applet – Compile the Hello. World. java onto Hello. World. class > javac Hello. World. java – Command line operation to run > appletviewer Hello. html – Use IE to read the HTML file. 交通大學資訊 程學系 蔡文能 第 36頁

Java Getting Started The Anatomy of a Java Applet (1/4) Importing Classes and Packages

Java Getting Started The Anatomy of a Java Applet (1/4) Importing Classes and Packages import java. applet. Applet; // import java. applet. *; import java. awt. Graphics; // import java. awt. *; public class Hello. World extends Applet { public void paint(Graphics g) { g. draw. String("Hello world!", 50, 25); } } =========================== public class Hello. World extends java. applet. Applet { public void paint(java. awt. Graphics g) { g. draw. String("Hello world!", 50, 25); } } ü Java. lang. * 是唯一不必 import 的 package 交通大學資訊 程學系 蔡文能 第 37頁

Java Getting Started The Anatomy of a Java Applet (2/4) Defining an Applet Subclass

Java Getting Started The Anatomy of a Java Applet (2/4) Defining an Applet Subclass import java. applet. Applet; import java. awt. Graphics; public class Hello. World extends Applet { public void paint(Graphics g) { g. draw. String("Hello world!", 50, 25); } } - Applets inherit a great deal of functionality from the Applet class. The most important is the ability to respond to browser requests. ü 拿 Java. applet. Applet. class 來擴充! 交通大學資訊 程學系 蔡文能 第 38頁

Java Getting Started The Anatomy of a Java Applet (3/4) Implementing Applet Methods import

Java Getting Started The Anatomy of a Java Applet (3/4) Implementing Applet Methods import java. applet. Applet; import java. awt. Graphics; public class Hello. World extends Applet { public void paint(Graphics g) { g. draw. String("Hello world!", 50, 25); } } - The Graphics object represents the applet's onscreen drawing context. - This applet draws the string "Hello world!" starting at location (50, 25). - The applet's coordinate system starts at (0, 0), which is at the upper left corner of the applet's display area. ü paint(Graphics) 這函數最重要 ! 交通大學資訊 程學系 蔡文能 第 39頁

Java Getting Started The Anatomy of a Java Applet (4/4) Running an Applet :

Java Getting Started The Anatomy of a Java Applet (4/4) Running an Applet : embed it into an HTML page <HTML> <HEAD><TITLE>A Simple Program</TITLE></HEAD> <BODY> Here is the output of my program: <APPLET CODE="Hello. World. class" WIDTH=150 HEIGHT=25> </APPLET> </BODY> </HTML> - The <APPLET> tag tells that the browser should load Hello. World. class. When the browser finds the class file, it loads it over the network, if necessary, onto the computer the browser is running on. - The WIDTH and HEIGHT attributes specify the size in pixels of the applet's display area. 交通大學資訊 程學系 蔡文能 第 40頁

Java Getting Started My. First. Coffee. java (Applet sample) p 1/2 import java. applet.

Java Getting Started My. First. Coffee. java (Applet sample) p 1/2 import java. applet. Applet; import java. awt. *; // Graphics, Font, Color, . . . public class My. First. Coffee extends Applet { /////// 注意檔名要與 Class 名相同 String s; // global 變數以便後續 function 也可用 public void init ( ) { //通常寫只會做一次的 作 s= get. Parameter("MSG"); // 抓<applet> 裡的參數 MSG放s } public void paint (Graphics g) { if(s == null ) s= "Ha Ha Ha !n. Heeee!"; // 在appletviewer抓不到ㄟ, 阿只好. . . (bug? 可能 HTML沒寫好) g. clear. Rect(0, 0, get. Size(). width, get. Size(). height); g. set. Color(Color. blue); // 所有顏色常數是小寫 ! 怪哉? 因為可以改 g. set. Font( new Font("Courier", Font. BOLD, 32) ); set. Background(Color. green); //這是Applet的method g. draw. String("Hey You!", 44, 80 ); 交通大學資訊 程學系 蔡文能 第 41頁

Java Getting Started My. First. Coffee. java (p 2/2) g. set. Color(Color. red); //

Java Getting Started My. First. Coffee. java (p 2/2) g. set. Color(Color. red); // 所有顏色常數是小寫 ! 變數! g. draw. Rect(55, 160 -32, 20*s. length() , 36); // red g. set. Color(Color. yellow); g. fill. Rect(57, 160 -32+2, 20*s. length()-4 , 36 -4); /// g. set. Font( new Font("Courier", Font. PLAIN, 24) ); g. draw. String("s. length()="+s. length(), 60, 220); g. set. Font( new Font("Courier", Font. BOLD, 32) ); g. set. Color(Color. magenta); // magenta g. draw. String(s, 60, 160 ); g. set. Font( new Font("標楷體", Font. BOLD, 32) ); g. set. Color(Color. orange); // orange g. draw. String(s, 60, 280 ); } } 交通大學資訊 程學系 蔡文能 第 42頁

Java Getting Started HTML to run My. First. Coffee <HTML> <BODY> <HR width=66%> <APPLET

Java Getting Started HTML to run My. First. Coffee <HTML> <BODY> <HR width=66%> <APPLET code="My. First. Coffee. class" width=580 height=320> <PARAM name="MSG" value="I am Big Head Lee 李大頭!"> <param name="P 2" value = "No use this time"> </applet> <!-- 注意在 APPLET tag 中的class檔名大小寫要與你的 class 檔完全相同! -------- --> <HR width=88%> 注意: 該. class檔在Server上要與此 HTML 檔放 </body> 一起; 否則要在 <applet …>裡指定 codebase </html> 交通大學資訊 程學系 蔡文能 第 43頁

Java Getting Started Applet My. First. Coffee is running 要如何把 HTML 檔 run 起來?

Java Getting Started Applet My. First. Coffee is running 要如何把 HTML 檔 run 起來? 當然可放到 WEB 網站. 若在 Windows XP, 則直接執行該 HTML 檔即可! 交通大學資訊 程學系 蔡文能 第 44頁

Java Getting Started Java Language Basics Variables and Data types Operators - 任何高階電腦語言都該有的指述: ü

Java Getting Started Java Language Basics Variables and Data types Operators - 任何高階電腦語言都該有的指述: ü /* 註解 */ //也是註解 ü宣告/定義 變數和常數 Arithmetic Operators Relational and Conditional Operators ü運算符號與運算式和 Assignment = Shift and Logical Operators • 算術, 關係運算, 邏輯 Assignment Operators ü{ compound statements; } Other Operators Expressions, Statements, and Blocks ü控制指述(control statements) Control Flow Statements - The while and do-while Statements The for Statement The if/else Statements The switch Statement Exception Handling Statements Branching Statements 交通大學資訊 程學系 蔡文能 ØSequence ØAlternative (selection) • if-else, switch ØLoop: for, while, do while ØFunction/procedure call 第 46頁

Java Getting Started Variables and Types in Java Primitive (simple) types - boolean (1

Java Getting Started Variables and Types in Java Primitive (simple) types - boolean (1 bit) byte (8 bit, signed) char (16 bit, UNICODE) short (16 bit, signed) int (32 bit, signed) long (64 bit, signed) float (32 bit, IEEE 754) double (64 bit, IEEE 754) Reference types (use pointers to access) - array types - class types - interface types 交通大學資訊 程學系 蔡文能 第 47頁

Java Getting Started Language Fundamentals Assignments - Copy values for primitive types - Assign

Java Getting Started Language Fundamentals Assignments - Copy values for primitive types - Assign only references for objects Parameter passing - Call by values Copy values for primitive types - Call by references Pass references for reference types. Objects access - accessing Objects through references - accessing null reference throws Null. Pointer. Exception 交通大學資訊 程學系 蔡文能 第 48頁

Java Getting Started Calss wrapper for primitive data types Integer: (in java. lang. Integer)

Java Getting Started Calss wrapper for primitive data types Integer: (in java. lang. Integer) class Integer { int i; Integer (int value) { i = value; }; . . . String to. String(); long. Value() {return (long)i; }. . . int i }. . . Integer a = new Integer(3849); Integer b = a; Integer c = b; a b c What are the internal data structures? 交通大學資訊 程學系 蔡文能 第 49頁

Java Getting Started Calss wrapper for primitive data types(cont. ) Boolean for boolean Byte

Java Getting Started Calss wrapper for primitive data types(cont. ) Boolean for boolean Byte for byte Character for char Short for short Integer for int Long for long Float for float Double for double 八大原始類別 Primitive data types Class Wrappers 交通大學資訊 程學系 蔡文能 第 50頁

Java Getting Started Arrays (different from array in C++) Arrays - Arrays are objects

Java Getting Started Arrays (different from array in C++) Arrays - Arrays are objects Arrays are dynamic Arrays are passed by reference Arrays are bounds checked (starts with 0 and ends with length - 1) int[] rgb = new int[3]; rgb[0] = 255; rgb[1] = 100; rgb[2] = 150; int avg = sum(rgb) / rgb. length ; int err = rgb[3]; //oops! Error!. . . int sum(int[] arr){ int result = 0; for (int i=arr. length; --i>=0; ) result += arr[i]; return result; } What are the internal operations? 交通大學資訊 程學系 蔡文能 第 51頁

Java Getting Started Operators Operator types: - Unary operators : require one operand, for

Java Getting Started Operators Operator types: - Unary operators : require one operand, for example, ++. - Binary operators : require two operands, for example, =. - Ternary operators require three operands. The only one in Java is ? : Which is a short-hand if-else statement. - Prefix : operator op - Postfix : op operator - Infix : op 1 operator op 2 交通大學資訊 程學系 蔡文能 expr ? op 1 : op 2 第 52頁

Java Getting Started Arithmetic Operators + op 1 + op 2 Adds op 1

Java Getting Started Arithmetic Operators + op 1 + op 2 Adds op 1 and op 2 - op 1 - op 2 Subtracts op 2 from op 1 * op 2 Multiplies op 1 by op 2 / op 1 / op 2 Divides op 1 by op 2 % op 1 % op 2 Computes the remainder of dividing op 1 by op 2 ++ op++ Increments op by 1; evaluates to value before incrementing ++ ++op Increments op by 1; evaluates to value after incrementing -- op-- Decrements op by 1; evaluates to value before decrementing -- --op Decrements op by 1; evaluates to value after decrementing 交通大學資訊 程學系 蔡文能 第 53頁

Java Getting Started Relational Operators Operator Use > op 1 > op 2 op

Java Getting Started Relational Operators Operator Use > op 1 > op 2 op 1 is greater than op 2 op 1 >= op 2 op 1 is greater than or equal to op 2 op 1 < op 2 op 1 is less than op 2 <= op 1 <= op 2 op 1 is less than or equal to op 2 == op 1 == op 2 op 1 and op 2 are equal != op 1 != op 2 op 1 and op 2 are not equal >= < 交通大學資訊 程學系 蔡文能 Return true if 第 54頁

Java Getting Started Conditional Operators 交通大學資訊 程學系 蔡文能 第 55頁

Java Getting Started Conditional Operators 交通大學資訊 程學系 蔡文能 第 55頁

Java Getting Started Bitwise Operators 交通大學資訊 程學系 蔡文能 第 56頁

Java Getting Started Bitwise Operators 交通大學資訊 程學系 蔡文能 第 56頁

Java Getting Started Assignment Operators 交通大學資訊 程學系 蔡文能 第 57頁

Java Getting Started Assignment Operators 交通大學資訊 程學系 蔡文能 第 57頁

Java Getting Started Expressions Definition: An expression is a series of variables, operators, and

Java Getting Started Expressions Definition: An expression is a series of variables, operators, and method calls that evaluates to a single value. - The data type of the result of an expression depends on the elements used in the expression. - A method call expression evaluates to the return value of the method. 交通大學資訊 程學系 蔡文能 第 58頁

Java Getting Started Operator Precedence 交通大學資訊 程學系 蔡文能 第 59頁

Java Getting Started Operator Precedence 交通大學資訊 程學系 蔡文能 第 59頁

Java Getting Started Control Flow Statements Control flow statements in Java Block - A

Java Getting Started Control Flow Statements Control flow statements in Java Block - A statement block is a series of statements within '{' and '}'. if (na < nb) { temp = na; na = nb; nb = temp; } 交通大學資訊 程學系 蔡文能 第 60頁

Java Getting Started if-else Statements The if-else Statement - The simple form of if

Java Getting Started if-else Statements The if-else Statement - The simple form of if can be written like this if ( boolean. Expression ) statement - The else block is executed if the if part is false. …… if (response == OK) { …… // code to perform OK action } else { …… // code to perform Cancel action } 交通大學資訊 程學系 蔡文能 第 61頁

Java Getting Started - Another form of the else statement if (testscore >= 90)

Java Getting Started - Another form of the else statement if (testscore >= 90) grade = 'A'; } else if (testscore grade = 'B'; } else if (testscore grade = 'C'; } else if (testscore grade = 'D'; } else { grade = 'F'; } 交通大學資訊 程學系 蔡文能 { >= 80) { >= 70) { >= 60) { 第 62頁

Java Getting Started switch Statements The switch Statement int month; . . . switch

Java Getting Started switch Statements The switch Statement int month; . . . switch (month) { case 1: System. out. println("January"); break; case 2: System. out. println("February"); break; . . . case 12: System. out. println("December"); break; } - break statements cause control to break out of the switch. 交通大學資訊 程學系 蔡文能 第 63頁

Java Getting Started - default statement at the end of the switch to handle

Java Getting Started - default statement at the end of the switch to handle other all cases. . switch (month) { case 1: System. out. println("January"); break; . . . case 12: System. out. println("December"); break; default: System. out. println("Hey, that's not a valid month!"); break; } 交通大學資訊 程學系 蔡文能 第 64頁

Java Getting Started for-Loop Statements for (initialization; termination; increment) statements; int i; int length

Java Getting Started for-Loop Statements for (initialization; termination; increment) statements; int i; int length = a. length; for (i = 0; i < length; i++) {. . . // do something to the i th element of a. . . } 交通大學資訊 程學系 蔡文能 第 65頁

Java Getting Started while -Loop Statements while ( boolean. Expression ) statement; k =

Java Getting Started while -Loop Statements while ( boolean. Expression ) statement; k = 0; while ( k < 9 ) ++k; while (in. read() != -1) { count++; System. out. println("Count = " + count); } 交通大學資訊 程學系 蔡文能 第 66頁

Java Getting Started Example: Counting characters In case I/O Exception import java. io. *;

Java Getting Started Example: Counting characters In case I/O Exception import java. io. *; public class Count { public static void count. Chars(Reader in) throws IOException { int count = 0; while (in. read() != -1) count++; System. out. println("Counted " + count + " chars. "); } //. . . main method omitted. . . } 交通大學資訊 程學系 蔡文能 第 67頁

Java Getting Started do-while Loop Statements do { statements } while (boolean. Expression); Example:

Java Getting Started do-while Loop Statements do { statements } while (boolean. Expression); Example: int c; Reader in; . . . do { c = in. read(); . . . } while (c != -1); 交通大學資訊 程學系 蔡文能 第 68頁

Java Getting Started Exception Handling Statements When an error occurs within a Java method,

Java Getting Started Exception Handling Statements When an error occurs within a Java method, the method can throw an exception to indicate to its caller that an error occurred and the type of error that occurred. The calling method can use the try, catch, and finally statements to catch and handle the exception. try { /* … java statements */ } catch ( /* exception object */ ) { /* … */ } finally { /* … * } 交通大學資訊 程學系 蔡文能 第 69頁

Java Getting Started Branching Statements Another form of the break statement. Name_Label: . .

Java Getting Started Branching Statements Another form of the break statement. Name_Label: . . . some Java Statements break statement. Name_Label; The continue statement - The unlabelled form. if( boolean. Expression ) continue; - The labeled form. continue statement. Name_Label; The return statement - Return a value. - Does not return a value. 交通大學資訊 程學系 蔡文能 return; return a+b; 第 70頁

Java Getting Started Multi-Level Branching public int index. Of(String str, int from. Index) {.

Java Getting Started Multi-Level Branching public int index. Of(String str, int from. Index) {. . . test: for (int i = offset + ((from. Index < 0) ? 0 : from. Index); i <= max ; i++) { int n = str. count; int j = i; int k = str. offset; while (n-- != 0) { if (v 1[j++] != v 2[k++]) { continue test; // continue; } if (. . . ) break test; } return i - offset; } return -1; } 交通大學資訊 程學系 蔡文能 第 71頁

Java Getting Started for Loop vs. while Loop (same as in C++) for(i=1 ;

Java Getting Started for Loop vs. while Loop (same as in C++) for(i=1 ; i<= 9 ; i++) { /* Loop body */ } i=1; for( ; i<= 9 ; ) { /* Loop body */ i++; } 交通大學資訊 程學系 蔡文能 These 3 structures have the same meaning 這三個寫法意義 完全一樣 i=1; while( i<= 9 ) { /* Loop body */ i++; } 第 72頁

Java Getting Started for Loop vs. while Loop (cont. ) for( ; ; )

Java Getting Started for Loop vs. while Loop (cont. ) for( ; ; ) ; ; while( ) { ; ; } == 0 != 0 交通大學資訊 程學系 蔡文能 第 73頁

Java Getting Started Inside the Applet An Applet is a Panel. Every applet is

Java Getting Started Inside the Applet An Applet is a Panel. Every applet is implemented by creating a subclass of the Applet class. 交通大學資訊 程學系 蔡文能 第 77頁

Java Getting Started A tipical Applet program (p. 1/2) import java. applet. Applet; import

Java Getting Started A tipical Applet program (p. 1/2) import java. applet. Applet; import java. awt. Graphics; public class Simple extends Applet { String. Buffer buffer; public void init() { buffer = new String. Buffer(); add. Item("initializing. . . "); } public void start() { add. Item("starting. . . "); } public void stop() { add. Item("stopping. . . "); } public void destroy() { add. Item("preparing for unloading. . . "); } /*. . . More on next page. . . */ 交通大學資訊 程學系 蔡文能 第 78頁

Java Getting Started A tipical Applet program (p. 2/2) void add. Item(String new. Word)

Java Getting Started A tipical Applet program (p. 2/2) void add. Item(String new. Word) { System. out. println(new. Word); buffer. append(new. Word); repaint(); } public void paint(Graphics g) { //Draw a Rectangle in the applet's display area. g. draw. Rect(0, 0, size(). width-1, size(). height 1); //Draw the current string inside the rectangle. g. draw. String(buffer. to. String(), 5, 15); } } 交通大學資訊 程學系 蔡文能 第 79頁

Java Getting Started The Life Cycle of an Applet Loading the Applet - When

Java Getting Started The Life Cycle of an Applet Loading the Applet - When an applet is loaded, here's what happens: An instance of the applet class is created. The applet initializes itself. The applet starts running. Leaving and Returning to the Applet's Page - Leaves the page -- go to another page -- the applet stopping itself. - Returns to the page, the applet can start itself again. - The same sequence occurs when the user iconifies and then reopens the window that contains the applet. Reloading the Applet - Reload applets -- unloading the applet and then loading it again. - Before unloaded, applet stop itself and then to perform a final cleanup. Applet can release any resources it holds. Quitting the Browser - Applet stop itself and do final cleanup before the browser exits. 交通大學資訊 程學系 蔡文能 第 80頁

Java Getting Started Methods for Applet public class Simple extends Applet {. . .

Java Getting Started Methods for Applet public class Simple extends Applet {. . . public void init() {. . . } public void start() {. . . } public void stop() {. . . } public void destroy() {. . . } initialize the applet when load (or reloaded). start the applet's execution when the applet's loaded. stop the applet's execution when the user leaves the page or quits the browser. destroy perform a final cleanup in preparation for unloading. 交通大學資訊 程學系 蔡文能 第 81頁

Java Getting Started Drawing and Event Handling class Simple extends Applet {. . .

Java Getting Started Drawing and Event Handling class Simple extends Applet {. . . public void paint(Graphics g) {. . . } paint - The basic display method. update - A method you can use along with paint to improve drawing performance. - The default one will clear the screen and then call paint(). So, this may cause blinking. 交通大學資訊 程學系 蔡文能 第 82頁

Java Getting Started Applets inherit a group of event-handling methods (e. g. , add.

Java Getting Started Applets inherit a group of event-handling methods (e. g. , add. Mouse. Listener(this)) from the Component class. import java. awt. event. Mouse. Listener; import java. awt. event. Mouse. Event; . . . Public class Simlpe extends Applet implements Mouse. Listener {. . . Public void init(){ add. Mouse. Listener(this); . . . }. . . Public void mouse. Clicked(Mouse. Event event){ add. Item(“click!…”); }. . . } 交通大學資訊 程學系 蔡文能 第 83頁

Java Getting Started A Simple Application using GUI Test the Gi. java - javac

Java Getting Started A Simple Application using GUI Test the Gi. java - javac Gi. java - java Gi. Gi GUI : Graphical User Interface 交通大學資訊 程學系 蔡文能 第 84頁

Java Getting Started Gi. java: A Simple Application using GUI import java. awt. *;

Java Getting Started Gi. java: A Simple Application using GUI import java. awt. *; (p 1. /4) import java. awt. event. *; public class Gi. Gi implements Action. Listener{ Frame f = new Frame("Window 2001"); Button b 1, b 2, b 3; Panel p; Button n, bq, big; int x. Size=300, y. Size=200; Dimension dim = Toolkit. get. Default. Toolkit(). get. Screen. Size(); Text. Area tx= new Text. Area("Hey 我愛 Gi. Gi", 5, 20, Text. Area. SCROLLBARS_HORIZONTAL_ONLY); public static void main( String s[]) { new Gi. Gi(); } /* More on next page. . . */ 交通大學資訊 程學系 蔡文能 第 85頁

Java Getting Started Gi. java (p 2. /4) public Gi. Gi() { // Constructor

Java Getting Started Gi. java (p 2. /4) public Gi. Gi() { // Constructor f. set. Size(x. Size, y. Size); f. set. Location(100, 100); tx. append("n=== ==== Text. Area tx="); tx. append(" new Text. Area("Hey 我愛 Gi. Gi", 5, 20, "); tx. append( " Text. Area. SCROLLBARS_HORIZONTAL_ONLY); n"); tx. append( "If 如果 Gi. Gi 不漂亮, 你還會覺得她的歌好聽嗎? n"); b 1=new Button("111"); b 2=new Button("222"); p = new Panel(); n= new Button("Haha. Hehehe"); p. add(n); bq=new Button("Quit"); p. add(bq); bq. set. Background(new Color(38, 38)); bq. set. Foreground(Color. red); big=new Button("Bigger"); p. add(big); big. set. Foreground(new Color(255, 0, 0)); n. set. Background(Color. green); 交通大學資訊 程學系 蔡文能 第 86頁

Java Getting Started Gi. java (p 3. /4) n. add. Action. Listener(this); //有事交給此程式中 //

Java Getting Started Gi. java (p 3. /4) n. add. Action. Listener(this); //有事交給此程式中 // 的action. Performed() b 1. add. Action. Listener(this); bq. add. Action. Listener(this); big. add. Action. Listener(this); f. add(tx, "Center"); //文字擺中間 f. add(b 1, "West"); ; f. add(b 2, "East"); f. add(p, "South"); f. show(); } /* Gi. Gi – the constructor */ 交通大學資訊 程學系 蔡文能 第 87頁

Java Getting Started Gi. java (p 4. /4) public void action. Performed(Action. Event evt){

Java Getting Started Gi. java (p 4. /4) public void action. Performed(Action. Event evt){ if(evt. get. Source() == n){ n. set. Background(Color. red); n. set. Label(" 777 "); } /* evt. . . == n */ if(evt. get. Source() == b 1) n. set. Label("Eleven"); if(evt. get. Source() == bq) System. exit(0); if(evt. get. Source() == big){ x. Size = (int) (x. Size*1. 2); if(x. Size>dim. width) x. Size= dim. width; y. Size = (int) (y. Size*1. 2); if(y. Size>dim. height) y. Size= dim. height; tx. append("n"+x. Size+ ", " + y. Size); f. set. Size(x. Size, y. Size); } f. validate(); // so that Layout Manager. . . } /* action. Performed */ } /* public class Gi. Gi */ 交通大學資訊 程學系 蔡文能 第 88頁

Java Run the Gi. java Getting Started Press the Bigger button 交通大學資訊 程學系 蔡文能

Java Run the Gi. java Getting Started Press the Bigger button 交通大學資訊 程學系 蔡文能 第 89頁

Java Getting Started Press the 111 button 交通大學資訊 程學系 蔡文能 第 90頁

Java Getting Started Press the 111 button 交通大學資訊 程學系 蔡文能 第 90頁

Java Getting Started Press the Eleven button 交通大學資訊 程學系 蔡文能 第 91頁

Java Getting Started Press the Eleven button 交通大學資訊 程學系 蔡文能 第 91頁

Java Getting Started Press the Bigger button again 交通大學資訊 程學系 蔡文能 第 92頁

Java Getting Started Press the Bigger button again 交通大學資訊 程學系 蔡文能 第 92頁

Java Getting Started Gi. Gi 2. java: A VERY Simple Application import java. awt.

Java Getting Started Gi. Gi 2. java: A VERY Simple Application import java. awt. *; import java. awt. event. *; public class Gi. Gi 2 { Frame f = new Frame("Window 2002"); Button b 1, b 2, b 3; Panel p; Button n; public static void main( String s[ ]) { new Gi. Gi 2( ); /* so that easily to change to Applet */ } public Gi. Gi 2( ) { // Constructor f. set. Size(300, 200); b 1=new Button("111"); b 2=new Button("222"); p = new Panel(); n= new Button("Haha. Hehehe"); p. add(n); n. set. Background(Color. green); f. add(b 1, "West"); f. add(b 2, "East"); f. add(p, "South"); /* Frame uses Boarder Layout manager */ f. show( ); } } 交通大學資訊 程學系 蔡文能 If you don’t understand the previous example, try this simple one! 第 93頁

Java Getting Started Run the Gi. Gi 2. javac Gi. Gi 2. java Gi.

Java Getting Started Run the Gi. Gi 2. javac Gi. Gi 2. java Gi. Gi 2 交通大學資訊 程學系 蔡文能 第 94頁

Java Getting Started Gi. Gi 3. java – stepwise refinement (p 1/2) import java.

Java Getting Started Gi. Gi 3. java – stepwise refinement (p 1/2) import java. awt. *; import java. awt. event. *; public class Gi. Gi 3 implements Action. Listener{ Frame f = new Frame("Window 2003"); Button b 1, b 2, b 3; Panel p; Button n; public static void main( String s[ ]) { new Gi. Gi 3(); /* easy to change to Applet */ } Let us add event handler 交通大學資訊 程學系 蔡文能 第 95頁

Java Gi. Gi 3. java Getting Started (p 2/2) public Gi. Gi 3( )

Java Gi. Gi 3. java Getting Started (p 2/2) public Gi. Gi 3( ) { // Constructor f. set. Size(300, 200); b 1=new Button("111"); b 2=new Button("222"); p = new Panel( ); f. add(p, "South"); f. add(b 1, "West"); f. add(b 2, "East"); Button bq = new Button("Quit"); n= new Button("Haha. Hehehe"); p. add(n); p. add(bq); n. set. Background(Color. green); n. add. Action. Listener(this); b 1. add. Action. Listener(this); f. show(); } public void action. Performed (Action. Event evt){ if(evt. get. Source() == n){ n. set. Background(Color. red); n. set. Label(" 777 "); } if(evt. get. Source() == b 1) n. set. Label("Eleven"); f. show(); // so that Layout Manager. . . } } 交通大學資訊 程學系 蔡文能 Let us add event handler 第 96頁

Java Getting Started Run the Gi. Gi 3. javac Gi. Gi 2. java Gi.

Java Getting Started Run the Gi. Gi 3. javac Gi. Gi 2. java Gi. Gi 2 What will happen if we press the "111" button? 交通大學資訊 程學系 蔡文能 第 97頁

Java Getting Started Run the Gi. Gi 3. java (cont. ) 按 "Quit" 有用嗎?

Java Getting Started Run the Gi. Gi 3. java (cont. ) 按 "Quit" 有用嗎? 交通大學資訊 程學系 蔡文能 第 98頁

Java JDK : J 2 SDK Getting Started http: //java. sun. com/j 2 se/

Java JDK : J 2 SDK Getting Started http: //java. sun. com/j 2 se/ 交通大學資訊 程學系 蔡文能 第 99頁

Java Getting Started http: //java. sun. com/javase/downloads/index. jsp 交通大學資訊 程學系 蔡文能 第 101頁

Java Getting Started http: //java. sun. com/javase/downloads/index. jsp 交通大學資訊 程學系 蔡文能 第 101頁

Java Getting Started JDK Installed Directory Tree The JDK has the directory structure shown

Java Getting Started JDK Installed Directory Tree The JDK has the directory structure shown below. jdk 1. 5. 0_<version> ____________|___________ | | | | bin lib | demo | | LICENSE | | | jre | | COPYRIGHT … … | __|__ | README. txt include | | readme. html bin lib 交通大學資訊 程學系 蔡文能 第 102頁

Java Getting Started Java IDE Best Java IDE - Borland JBuilder, Borland Software -

Java Getting Started Java IDE Best Java IDE - Borland JBuilder, Borland Software - Eclipse, Eclipse. org - Intelli. J IDEA, Jet. Brains 交通大學資訊 程學系 蔡文能 第 105頁

Java Getting Started Features of most IDE: Full documentation of Java libraries at hand.

Java Getting Started Features of most IDE: Full documentation of Java libraries at hand. Can insert templates. Syntax coloring. Can indent program and find the matching brace. Can easily comment-out code fragments. Good printing facilities. Syntax errors are highlighted (even if another file needs to be opened). … and it does not interfere in your programming! 交通大學資訊 程學系 蔡文能 第 106頁 Ready-4

Java Getting Started Java-XML tools Best Java-XML Tool - JAXB (Java Architecture for XML

Java Getting Started Java-XML tools Best Java-XML Tool - JAXB (Java Architecture for XML Binding), Sun Microsystems - Xalan-Java 2. 5, The Apache XML Project - Xerces 2 Java Parser 2. 4, The Apache XML Project 交通大學資訊 程學系 蔡文能 第 107頁

Java Getting Started Introduction to Java Programming 謝謝捧場 http: //www. csie. nctu. edu. tw/~tsaiwn/java/

Java Getting Started Introduction to Java Programming 謝謝捧場 http: //www. csie. nctu. edu. tw/~tsaiwn/java/ 蔡文能 交通大學資訊 程學系 蔡文能 第 108頁