View
346
Download
1
Embed Size (px)
Citation preview
交通大學資訊工程學系
Programming in Java
Getting Started
蔡文能交通大學資訊工程學系[email protected]
http://www.csie.nctu.edu.tw/~tsaiwn/java/
交通大學資訊工程學系 蔡文能 第 2頁
Java Getting Started
OutlineJava History …
Java vs. C++
Compilation and Interpretation
Java Platform
Java Applications
Java Applets
Language Basics
Inside the Applets
Applications using GUI
More about Applets
交通大學資訊工程學系 蔡文能 第 3頁
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 McNealy and Bill Joy.
交通大學資訊工程學系 蔡文能 第 4頁
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.
交通大學資訊工程學系 蔡文能 第 5頁
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 FirstPerson 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.
交通大學資訊工程學系 蔡文能 第 6頁
Java Getting Started
Start Licensing
September 1994 Jonathon Payne and Naughton start writing "WebRunner," a
Mosaic-like browser later renamed "HotJava“. HotJava prototype is first demonstrated to Sun executives.
May 1995 Sun formally announces Java and HotJava at SunWorld '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.
交通大學資訊工程學系 蔡文能 第 7頁
Java Getting Started
Quick GrowthOctober 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.
交通大學資訊工程學系 蔡文能 第 8頁
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 SunWorld 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/java2/whatis/1996/
Java technology: An Early History - 1998 http://java.sun.com/features/1998/05/birthday.html
交通大學資訊工程學系 蔡文能 第 9頁
Java Getting Started
Sun announced Java on 1995/05/23
交通大學資訊工程學系 蔡文能 第 10頁
Java Getting Started
交通大學資訊工程學系 蔡文能 第 11頁
Java Getting Started
交通大學資訊工程學系 蔡文能 第 12頁
Java Getting Started
交通大學資訊工程學系 蔡文能 第 13頁
Java Getting Started
交通大學資訊工程學系 蔡文能 第 14頁
Java Getting Started
JSP
交通大學資訊工程學系 蔡文能 第 15頁
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 DataBase 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)
交通大學資訊工程學系 蔡文能 第 16頁
Java Getting Started
java.applet, java.awt, java.io, java.lang, java.net, java.util
java.math, java.rmi, java.security, java.sql, java.text, java.beans
javax.accessibility, javax.swing, org.omg
javax.naming, javax.sound, javax.transaction
java.nio, javax.imageio,javax.net, javax.print,javax.security, org.w3c
javax.activity,javax.management
JDK 1.08 packages212 classes
JDK 1.123 packages504 classes
JDK 1.259 packages1520 classes
JDK 1.377 packages1595 classes
JDK 1.4103 packages2175 classes
JDK 1.5131 packages2656 classes
New Events
Inner class
Object Serialization
Jar Files
International
Reflection
JDBC
RMI
JFC/Swing
Drag and Drop
Java2D
CORBA
JNDI
Java Sound
Timer
Regular ExpLoggingAssertionsNIO
交通大學資訊工程學系 蔡文能 第 17頁
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.
Java == C++--++
Java
C++
C
交通大學資訊工程學系 蔡文能 第 18頁
Java Getting Started
Added FeaturesTypes: (8 primitive types and their class wrappers) boolean (1bit), byte (8 bit signed), char (16 bit, Unicode), short (16bit), int (32bit), long (64bit), float, double, String, Array (as object)
Multi-level break 從此真的可以不必用 goto (拿掉了 )Interfaces 不可多重繼承 ; 但可 implement多個介面Packages 把相關的 class 集合在同一個子目錄Automatic garbage collection 不再有 memory leakingMultithread and synchronizationException handling ( 做得比 C++ 好 ) (C只有 signal和longjmp)Runtime type checking
Java == C++--++
交通大學資訊工程學系 蔡文能 第 19頁
Java Getting Started
Compilation and Interpretation
Compilation Source code Bytecode
MyProgram.java MyProgram.class (注意大小寫 )
Interpretation Bytecode
the machine code instructions for the Java Virtual Machine.
the platform-independent codes interpreted by the Java interpreter.
交通大學資訊工程學系 蔡文能 第 20頁
Java Getting Started
Write Once, Run Everywhere
Other sayings, Write once, test everywhere. Write once, tune everywhere.
交通大學資訊工程學系 蔡文能 第 21頁
Java Getting Started
Advantages of Java
Platform independent, portable and interoperable
Mobile over distributed systems
Simple, Object-Oriented
Robust and secure
Reasonably good performance
Interpreted (bytecode)
Multithreaded
. . .
Java
C++
C
交通大學資訊工程學系 蔡文能 第 22頁
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.
交通大學資訊工程學系 蔡文能 第 23頁
Java Getting Started
Java Platform
Java Virtual Machine (JVM)
Java API where you need to learn more.
API :Application Programming Interface
交通大學資訊工程學系 蔡文能 第 24頁
Java Getting Started
Java Editions
J2EE, J2SE, J2ME
交通大學資訊工程學系 蔡文能 第 25頁
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
交通大學資訊工程學系 蔡文能 第 26頁
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: http://java.sun.com/
交通大學資訊工程學系 蔡文能 第 28頁
Java Getting Started
要看
!
Of course you can visit home of java: http://java.sun.com/
交通大學資訊工程學系 蔡文能 第 29頁
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.
交通大學資訊工程學系 蔡文能 第 30頁
Java Getting Started
Java Applications (standalone programs)
A Java Application is a standalone program.
The source code of HelloWorldApp.java:
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. } }
public class name should be same as the name of Java Source File name
交通大學資訊工程學系 蔡文能 第 31頁
Java Getting Started
The main method
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.
public static void main(String[] args) { ... }
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 image.gif
交通大學資訊工程學系 蔡文能 第 32頁
Java Getting Started
Compiling and Run the Application
Compiling the source file Command line operation
> javac HelloWorldApp.java This operation generates HelloWorld.class Javac is the Java Compiler
Run the Application Command line operation
> java HelloWorldApp 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)
交通大學資訊工程學系 蔡文能 第 33頁
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
交通大學資訊工程學系 蔡文能 第 34頁
Java Getting Started
Javadoc
See more in http://java.sun.com/j2se/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 setToolTipText(String text) {
More tags* @author (classes and interfaces only, required)* @version (classes and interfaces only, required) (see footnote 1)* * @param (methods and constructors only)* @return (methods only)* @exception (@throws is a synonym added in Javadoc 1.2)* @see * @since * @serial (or @serialField or @serialData)* @deprecated (see How and When To Deprecate APIs)
交通大學資訊工程學系 蔡文能 第 35頁
Java Getting Started
An Example of Applet
A Java Applet runs in web browser.
The source code of HelloWorld.java:
import java.applet.Applet;import java.awt.Graphics;
public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }
交通大學資訊工程學系 蔡文能 第 36頁
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="HelloWorld.class" WIDTH=150 HEIGHT=25></APPLET></BODY></HTML>
• Run the Applet– Compile the HelloWorld.java onto HelloWorld.class
> javac HelloWorld.java– Command line operation to run
> appletviewer Hello.html– Use IE to read the HTML file.
交通大學資訊工程學系 蔡文能 第 37頁
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 HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }
=====================================================
public class HelloWorld extends java.applet.Applet { public void paint(java.awt.Graphics g) { g.drawString("Hello world!", 50, 25); } }
Java.lang.* 是唯一不必 import 的package
交通大學資訊工程學系 蔡文能 第 38頁
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 HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("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 來擴充 !
交通大學資訊工程學系 蔡文能 第 39頁
Java Getting Started
The Anatomy of a Java Applet (3/4)Implementing Applet Methods
import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("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) 這函數最重 要 !
交通大學資訊工程學系 蔡文能 第 40頁
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="HelloWorld.class" WIDTH=150 HEIGHT=25> </APPLET> </BODY> </HTML>
The <APPLET> tag tells that the browser should load HelloWorld.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.
交通大學資訊工程學系 蔡文能 第 41頁
Java Getting Started
MyFirstCoffee.java (Applet sample) p1/2 import java.applet.Applet; import java.awt.*; // Graphics, Font, Color, ... public class MyFirstCoffee extends Applet { ///////////// 注意檔名要與 Class 名相同 String s; // global 變數以便後續 function 也可用 public void init ( ) { //通常寫只會做一次的工作 s= getParameter("MSG"); // 抓 <applet> 裡的參數 MSG放 s } public void paint (Graphics g) { if(s == null ) s= "Ha Ha Ha !\nHee Heeee!"; // 在 appletviewer抓不到ㄟ , 阿只好 ...(bug? 可能 HTML沒寫好 )
g.clearRect(0, 0, getSize().width, getSize().height); g.setColor(Color.blue); // 所有顏色常數是小寫 ! 怪哉 ? 因為可以改 g.setFont( new Font("Courier", Font.BOLD, 32) ); setBackground(Color.green); //這是 Applet的method g.drawString("Hey You!", 44, 80 );
交通大學資訊工程學系 蔡文能 第 42頁
Java Getting Started
MyFirstCoffee.java (p2/2)
g.setColor(Color.red); // 所有顏色常數是小寫 ! 變數 ! g.drawRect(55, 160-32, 20*s.length() , 36); // red g.setColor(Color.yellow); g.fillRect(57, 160-32+2, 20*s.length()-4 , 36-4); /// g.setFont( new Font("Courier", Font.PLAIN, 24) ); g.drawString("s.length()="+s.length(), 60, 220); g.setFont( new Font("Courier", Font.BOLD, 32) ); g.setColor(Color.magenta); // magenta g.drawString(s, 60, 160 ); g.setFont( new Font("標楷體 ", Font.BOLD, 32) ); g.setColor(Color.orange); // orange g.drawString(s, 60, 280 ); } }
交通大學資訊工程學系 蔡文能 第 43頁
Java Getting Started
HTML to run MyFirstCoffee
<HTML>
<BODY>
<HR width=66%>
<APPLET code="MyFirstCoffee.class" width=580 height=320>
<PARAM name="MSG" value="I am Big Head Lee 李大頭 !">
<param name="P2" value = "No use this time">
</applet>
<!-- 注意 在 APPLET tag 中的 class檔名大小寫要與你的 class 檔完全相同 !
--------------- -->
<HR width=88%>
</body>
</html>
注意 : 該 .class檔在 Server 上要與此HTML 檔放一起 ; 否則要在 <applet …>裡
指定 codebase
交通大學資訊工程學系 蔡文能 第 44頁
Java Getting Started
Applet MyFirstCoffee is running
要如何把 HTML 檔 run 起來 ? 當然可放到 WEB 網站 .
若在 Windows XP, 則直接執行該 HTML 檔即可 !
交通大學資訊工程學系 蔡文能 第 45頁
Java Getting Started
唐詩宋詞
Take a Break! 蝶戀花 柳永 .
獨倚危樓風細細。
望極春愁,黯黯生天際。
草色山光殘照裏,
無人會得憑闌意,
也擬疏狂圖一醉。
對酒當歌,強樂還無味。
衣帶漸寬終不悔,為伊銷得人憔悴。
為愛痴狂 劉若英
我 從 春 天 走 來 你 在 秋 天 說 要 分 開 說 好 不 為 你 憂 傷 但 心 情 怎 會 無 恙
為 何 總 是 這 樣 在 我 心 中 深 藏 著 你 想 要 問 你 想 不 想 陪 我 到 地 老 天 荒
如 果 愛 情 這 樣 憂 傷 為 何 不 讓 我 分 享 日 夜 都 問 你 也 不 回 答 怎 麼 你 會 變 這 樣
想 要 問 問 你 敢 不 敢 像 你 說 過 的 那 樣 的 愛 我 ﹝ 想 要 問 問 你 敢 不 敢 ﹞
像 我 這 樣 為 愛 癡 狂 到 底 你 會 怎 麼 想◎為愛痴狂收錄在劉若英個人專輯『少女小漁劉若英的美麗與哀愁』中。
浪淘沙 李 煜
簾外雨潺潺,春意闌珊。
羅衾不耐五更寒。
夢裡不知身是客,一餉貪歡。
獨自莫憑闌,無限江山,別時容易見時難。
流水落花春去也,天上人間。
交通大學資訊工程學系 蔡文能 第 46頁
Java Getting Started
Java Language BasicsVariables and Data typesOperators Arithmetic Operators Relational and Conditional Operators Shift and Logical Operators Assignment Operators Other Operators
Expressions, Statements, and Blocks Control Flow Statements The while and do-while Statements The for Statement The if/else Statements The switch Statement Exception Handling Statements Branching Statements
任何高階電腦語言都該有的指述 :
/* 註解 */ //也是註解
宣告 / 定義 變數和常數
運算符號與運算式和 Assignment =
•算術 , 關係運算 , 邏輯
{ compound statements; }
控制指述 (control statements)
Sequence
Alternative (selection)
•if-else, switch
Loop: for, while, do while
Function/procedure call
交通大學資訊工程學系 蔡文能 第 47頁
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 (32bit, 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
交通大學資訊工程學系 蔡文能 第 48頁
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 referencesPass references for reference types.
Objects access accessing Objects through references accessing null reference throws NullPointerException
交通大學資訊工程學系 蔡文能 第 49頁
Java Getting Started
Calss wrapper for primitive data typesInteger: (in java.lang.Integer)
class Integer { int i;
Integer (int value) { i = value; }; ...... String toString(); long longValue() {return (long)i;} ......}...... Integer a = new Integer(3849);Integer b = a;Integer c = b;
int i
a b c
What are the internal data structures?
交通大學資訊工程學系 蔡文能 第 50頁
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 typesClass
Wrappers
八大原始類別
交通大學資訊工程學系 蔡文能 第 51頁
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?
交通大學資訊工程學系 蔡文能 第 52頁
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 : op1 operator op2 expr ? op1 : op2
交通大學資訊工程學系 蔡文能 第 53頁
Java Getting Started
Arithmetic Operators
Arithmetic Operators+ op1 + op2 Adds op1 and op2
- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Computes the remainder of dividing op1 by op2
++ 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
交通大學資訊工程學系 蔡文能 第 54頁
Java Getting Started
Relational Operators Operator Use Return true if
> op1 > op2 op1 is greater than op2
>= op1 >= op2 op1 is greater than or equal to op2
< op1 < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal
交通大學資訊工程學系 蔡文能 第 55頁
Java Getting Started
Conditional Operators
Operator Use Return true if
&& op1 && op2 op1 and op2 are both true,conditionally evaluates op2
|| op1 || op2 either op1 or op2 is true,conditionally evaluates op2
! ! op op is false
& op1 & op2 op1 and op2 are both true, alwaysevaluates op1 and op2
| op1 | op2 either op1 or op2 is true, alwaysevaluates op1 and op2
交通大學資訊工程學系 蔡文能 第 56頁
Java Getting Started
Bitwise OperatorsOperator Use Operation
>> op1 >> op2 shift bits of op1 right bydistance op2
<< op1 << op2 shift bits of op1 left bydistance op2
>>> op1 >>> op2 shift bits of op1 right bydistance op2 (unsigned)
& op1 & op2 bitwise and
| op1 | op2 bitwise or
^ op1 ^ op2 bitwise oxr
~ ~ op bitwise complement
交通大學資訊工程學系 蔡文能 第 57頁
Java Getting Started
Assignment Operators
Operator Use Equivalent to+= op1 += op2 op1 = op1 + op2-= op1 -= op2 op1 = op1 - op2*= op1 *= op2 op1 = op1 * op2/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2&= op1 &= op2 op1 = op1 & op2|= op1 |= op2 op1 = op1 | op2^= op1 ^= op2 op1 = op1 ^ op2
<<= op1 <<= op2 op1 = op1 << op2>>= op1 >>= op2 op1 = op1 >> op2
>>>= op1 >>>= op2 op1 = op1 >>> op2
交通大學資訊工程學系 蔡文能 第 58頁
Java Getting Started
ExpressionsDefinition: 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.
交通大學資訊工程學系 蔡文能 第 59頁
Java Getting Started
Operator Precedencepostfix operators [] . (params) expr++ expr--unary operators ++expr --expr +expr -expr ~ !creation or cast new (type)exprmultiplicative * / %additive + -shift << >> >>>relational < > <= >= instanceofequality == !=bitwise AND &bitwise exclusive OR ^bitwise inclusive OR |logical AND &&logical OR ||conditional ? :assignment = += -= *= /= %= &= ^= |=
<<= >>= >>>=
交通大學資訊工程學系 蔡文能 第 60頁
Java Getting Started
Control Flow StatementsControl flow statements in Java
Statement Keyword Decision making if-else, switch-case Loop for, while, do-while Exception try-catch-finally, throw Branching break, continue, label: , return
Block A statement block is a series of statements within '{' and '}'.
if (na < nb) {
temp = na;
na = nb; nb = temp;
}
交通大學資訊工程學系 蔡文能 第 61頁
Java Getting Started
if-else Statements
The if-else Statement The simple form of if can be written like this
if ( booleanExpression )
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
}
交通大學資訊工程學系 蔡文能 第 62頁
Java Getting Started
Another form of the else statement
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
交通大學資訊工程學系 蔡文能 第 63頁
Java Getting Started
switch StatementsThe 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.
交通大學資訊工程學系 蔡文能 第 64頁
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;
}
交通大學資訊工程學系 蔡文能 第 65頁
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
. . .
}
交通大學資訊工程學系 蔡文能 第 66頁
Java Getting Started
while -Loop Statements
while ( booleanExpression ) statement;
k = 0;
while ( k < 9 ) ++k;
while (in.read() != -1) {
count++;System.out.println("Count = " + count);
}
交通大學資訊工程學系 蔡文能 第 67頁
Java Getting Started
Example: Counting characters
import java.io.*;public class Count {
public static void countChars(Reader in) throws IOException
{ int count = 0; while (in.read() != -1)
count++; System.out.println("Counted " + count + " chars."); } // ... main method omitted ...}
In case I/O Exception
交通大學資訊工程學系 蔡文能 第 68頁
Java Getting Started
do-while Loop Statementsdo {
statements
} while (booleanExpression);
Example:int c;
Reader in;
. . .
do {
c = in.read();
. . .
} while (c != -1);
交通大學資訊工程學系 蔡文能 第 69頁
Java Getting Started
Exception Handling StatementsWhen 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 */ ) { /* … */
} catch ( /* exception object */ ) { /* … */
} finally { /* … * }
交通大學資訊工程學系 蔡文能 第 70頁
Java Getting Started
Branching StatementsAnother form of the break statement
statementName_Label:
. . . some Java Statements
break statementName_Label;
The continue statement The unlabelled form. if( booleanExpression ) continue; The labeled form. continue statementName_Label;
The return statement Return a value. return; Does not return a value. return a+b;
交通大學資訊工程學系 蔡文能 第 71頁
Java Getting Started
Multi-Level Branchingpublic int indexOf(String str, int fromIndex) {. . . . . . test: for (int i = offset + ((fromIndex < 0) ? 0 :fromIndex); i <= max ; i++) { int n = str.count; int j = i; int k = str.offset; while (n-- != 0) { if (v1[j++] != v2[k++]) { continue test; // continue; }
if ( ... ) break test; } return i - offset; } return -1; }
交通大學資訊工程學系 蔡文能 第 72頁
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++;}
i=1;while( i<= 9 ){ /* Loop body */ i++;}
These 3 structures have These 3 structures have the same meaningthe same meaning
這三個寫法意義這三個寫法意義完全一樣完全一樣
交通大學資訊工程學系 蔡文能 第 73頁
Java Getting Started
for Loop vs. while Loop (cont.)
for( ; ; ) ;
;while( ){ ; ;}
== 0
!= 0
交通大學資訊工程學系 蔡文能 第 74頁
Java Getting Started
while Loop example
拿盤子 , 拿飲料 , 找好位子 ;while(肚子還餓 ){ 吃一盤 ; 喝一杯 ; 喘一口氣 ;}結帳 ; 回家 ;
All you can eat !
交通大學資訊工程學系 蔡文能 第 75頁
Java Getting Started
while Loop example(cont.)
拿盤子 , 拿飲料 , 找好位子 ;while( 肚子還餓 ){ 吃一盤 ; if( 有急事 || 很飽了 )break; if(不會渴 ) continue; 喝一杯 ; 喘一口氣 ;}結帳 ; 回家 ;
不夠本
All you can eat !
交通大學資訊工程學系 蔡文能 第 76頁
Java Getting Started
唐詩宋詞
Take a Break! 蝶戀花 柳永 .
獨倚危樓風細細。
望極春愁,黯黯生天際。
草色山光殘照裏,
無人會得憑闌意,
也擬疏狂圖一醉。
對酒當歌,強樂還無味。
衣帶漸寬終不悔,為伊銷得人憔悴。
為愛痴狂 劉若英
我 從 春 天 走 來 你 在 秋 天 說 要 分 開 說 好 不 為 你 憂 傷 但 心 情 怎 會 無 恙
為 何 總 是 這 樣 在 我 心 中 深 藏 著 你 想 要 問 你 想 不 想 陪 我 到 地 老 天 荒
如 果 愛 情 這 樣 憂 傷 為 何 不 讓 我 分 享 日 夜 都 問 你 也 不 回 答 怎 麼 你 會 變 這 樣
想 要 問 問 你 敢 不 敢 像 你 說 過 的 那 樣 的 愛 我 ﹝ 想 要 問 問 你 敢 不 敢 ﹞
像 我 這 樣 為 愛 癡 狂 到 底 你 會 怎 麼 想◎為愛痴狂收錄在劉若英個人專輯『少女小漁劉若英的美麗與哀愁』中。
浪淘沙 李 煜
簾外雨潺潺,春意闌珊。
羅衾不耐五更寒。
夢裡不知身是客,一餉貪歡。
獨自莫憑闌,無限江山,別時容易見時難。
流水落花春去也,天上人間。
交通大學資訊工程學系 蔡文能 第 77頁
Java Getting Started
Inside the Applet
An Applet is a Panel.
Every applet is implemented by creating a subclass of the Applet class.
交通大學資訊工程學系 蔡文能 第 78頁
Java Getting Started
A tipical Applet program (p.1/2)import java.applet.Applet;import java.awt.Graphics;
public class Simple extends Applet {StringBuffer buffer;
public void init() {buffer = new StringBuffer();addItem("initializing... ");
} public void start() {
addItem("starting... ");} public void stop() {
addItem("stopping... ");}public void destroy() {
addItem("preparing for unloading...");}
/* ... More on next page... */
交通大學資訊工程學系 蔡文能 第 79頁
Java Getting Started
A tipical Applet program (p.2/2)
void addItem(String newWord) {System.out.println(newWord);
buffer.append(newWord); repaint();
}
public void paint(Graphics g) {//Draw a Rectangle in the applet's display area.
g.drawRect(0, 0, size().width-1, size().height-1);
//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15);
}}
交通大學資訊工程學系 蔡文能 第 80頁
Java Getting Started
The Life Cycle of an AppletLoading 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.
交通大學資訊工程學系 蔡文能 第 81頁
Java Getting Started
Methods for Applet
init initialize the applet when load (or reloaded).
start start the applet's execution when the applet's loaded.
stop stop the applet's execution when the user leaves the page or quits the browser.
destroy perform a final cleanup in preparation for unloading.
public class Simple extends Applet { . . . public void init() { . . . } public void start() { . . . } public void stop() { . . . } public void destroy() { . . . } . . .}
交通大學資訊工程學系 蔡文能 第 82頁
Java Getting Started
Drawing and Event Handling
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.
class Simple extends Applet { . . . public void paint(Graphics g) {
. . . } . . .}
交通大學資訊工程學系 蔡文能 第 83頁
Java Getting Started
Applets inherit a group of event-handling methods (e.g., addMouseListener(this)) from the Component class.
import java.awt.event.MouseListener;import java.awt.event.MouseEvent;. . .Public class Simlpe extends Applet implements MouseListener {
. . .Public void init(){
addMouseListener(this);. . .
}. . .Public void mouseClicked(MouseEvent event){
addItem(“click!…”);}
. . .}
交通大學資訊工程學系 蔡文能 第 84頁
Java Getting Started
A Simple Application using GUI
Test the GiGi.java javac GiGi.java java GiGi
GUI : Graphical User Interface
交通大學資訊工程學系 蔡文能 第 85頁
Java Getting Started
GiGi.java: A Simple Application using GUIimport java.awt.*;import java.awt.event.*;public class GiGi implements ActionListener{ Frame f = new Frame("Window 2001"); Button b1,b2,b3; Panel p; Button n, bq, big; int xSize=300, ySize=200; Dimension dim =
Toolkit.getDefaultToolkit().getScreenSize(); TextArea tx= new TextArea("Hey 我愛 GiGi",
5,20,TextArea.SCROLLBARS_HORIZONTAL_ONLY); public static void main( String s[]) { new GiGi(); }
/* More on next page ... */
(p1./4)
交通大學資訊工程學系 蔡文能 第 86頁
Java Getting Started
GiGi.java (p2./4) public GiGi() { // Constructor f.setSize(xSize,ySize); f.setLocation(100,100); tx.append("\n=== ==== ==== TextArea tx="); tx.append(" new TextArea(\"Hey 我愛 GiGi\",
5,20,"); tx.append(
" TextArea.SCROLLBARS_HORIZONTAL_ONLY);\n"); tx.append(
"If 如果 GiGi 不漂亮 , 你還會覺得她的歌好聽嗎 ?\n"); b1=new Button("111"); b2=new Button("222"); p = new Panel(); n= new Button("HahaHehehe");
p.add(n); bq=new Button("Quit"); p.add(bq); bq.setBackground(new Color(38,38,38));
bq.setForeground(Color.red); big=new Button("Bigger"); p.add(big); big.setForeground(new Color(255,0,0)); n.setBackground(Color.green);
交通大學資訊工程學系 蔡文能 第 87頁
Java Getting Started
GiGi.java (p3./4)
n.addActionListener(this); //有事交給此程式中 // 的 actionPerformed()
b1.addActionListener(this); bq.addActionListener(this); big.addActionListener(this); f.add(tx,"Center"); //文字擺中間 f.add(b1,"West"); ; f.add(b2,"East"); f.add(p,"South");
f.show();} /* GiGi – the constructor */
交通大學資訊工程學系 蔡文能 第 88頁
Java Getting Started
GiGi.java (p4./4) public void actionPerformed(ActionEvent evt){ if(evt.getSource() == n){ n.setBackground(Color.red);
n.setLabel(" 777 "); } /* evt... == n */ if(evt.getSource() == b1) n.setLabel("Eleven"); if(evt.getSource() == bq) System.exit(0); if(evt.getSource() == big){ xSize = (int) (xSize*1.2);
if(xSize>dim.width) xSize= dim.width; ySize = (int) (ySize*1.2);
if(ySize>dim.height) ySize= dim.height; tx.append("\n"+xSize+ "," + ySize); f.setSize(xSize,ySize); } f.validate(); // so that Layout Manager ... } /* actionPerformed */} /* public class GiGi */
交通大學資訊工程學系 蔡文能 第 89頁
Java Getting Started
Run the GiGi.java Press the Bigger button
交通大學資訊工程學系 蔡文能 第 90頁
Java Getting Started
Press the 111 button
交通大學資訊工程學系 蔡文能 第 91頁
Java Getting Started
Press the ElevenEleven button
交通大學資訊工程學系 蔡文能 第 92頁
Java Getting Started
Press the Bigger button again
交通大學資訊工程學系 蔡文能 第 93頁
Java Getting Started
GiGi2.java: A VERY Simple Applicationimport java.awt.*;import java.awt.event.*;public class GiGi2 { Frame f = new Frame("Window 2002"); Button b1, b2, b3; Panel p; Button n; public static void main( String s[ ]) { new GiGi2( ); /* so that easily to change to Applet */ } public GiGi2( ) { // Constructor f.setSize(300,200); b1=new Button("111"); b2=new Button("222"); p = new Panel(); n= new Button("HahaHehehe"); p.add(n); n.setBackground(Color.green); f.add(b1,"West"); f.add(b2,"East"); f.add(p,"South"); /* Frame uses Boarder Layout manager */ f.show( ); }}
If you don’t understand the previous example, try this simple one!
交通大學資訊工程學系 蔡文能 第 94頁
Java Getting Started
Run the GiGi2.java
javac GiGi2.java
java GiGi2
交通大學資訊工程學系 蔡文能 第 95頁
Java Getting Started
GiGi3.java – stepwise refinement (p1/2)
import java.awt.*;
import java.awt.event.*;
public class GiGi3 implements ActionListener{
Frame f = new Frame("Window 2003");
Button b1,b2,b3;
Panel p; Button n;
public static void main( String s[ ]) {
new GiGi3(); /* easy to change to Applet */
}
Let us add event handler
交通大學資訊工程學系 蔡文能 第 96頁
Java Getting Started
GiGi3.java (p2/2) public GiGi3( ) { // Constructor f.setSize(300,200); b1=new Button("111"); b2=new Button("222"); p = new Panel( ); f.add(p,"South"); f.add(b1,"West"); f.add(b2,"East"); Button bq = new Button("Quit"); n= new Button("HahaHehehe"); p.add(n); p.add(bq); n.setBackground(Color.green); n.addActionListener(this); b1.addActionListener(this); f.show(); } public void actionPerformed (ActionEvent evt){ if(evt.getSource() == n){ n.setBackground(Color.red); n.setLabel(" 777 ");} if(evt.getSource() == b1) n.setLabel("Eleven"); f.show(); // so that Layout Manager ... }} Let us add event handler
交通大學資訊工程學系 蔡文能 第 97頁
Java Getting Started
Run the GiGi3.java
javac GiGi2.java
java GiGi2
What will happen if we press the "111" button?
交通大學資訊工程學系 蔡文能 第 98頁
Java Getting Started
Run the GiGi3.java (cont.)
按 "Quit" 有用嗎 ?
交通大學資訊工程學系 蔡文能 第 99頁
Java Getting Started
JDK : J2SDKhttp://java.sun.com/j2se/
交通大學資訊工程學系 蔡文能 第 100頁
Java Getting Started
交通大學資訊工程學系 蔡文能 第 101頁
Java Getting Started
http://java.sun.com/javase/downloads/index.jsp
交通大學資訊工程學系 蔡文能 第 102頁
Java Getting Started
JDK Installed Directory TreeThe JDK has the directory structure shown below.
jdk1.5.0_<version> _______________________|______________________ | | | | | | | | | | | | | bin lib | demo || | | LICENSE | | | jre| | COPYRIGHT … … | __|__| README.txt include | |
readme.html bin lib
交通大學資訊工程學系 蔡文能 第 103頁
Java Getting Started
工欲善其事 , 必先利其器http://www.csie.nctu.edu.tw/document/java/
或是 舊交大資工網頁 資源服務 網路資源 Java 的說明書http://www.cs.nctu.edu.tw/ (新交大資工網頁 )相關連結 網路資源 Java 的說明書
交通大學資訊工程學系 蔡文能 第 104頁
Java Getting Started
交通大學資訊工程學系 蔡文能 第 105頁
Java Getting Started
Java IDE
Best Java IDE Borland JBuilder, Borland Software Eclipse, Eclipse.org IntelliJ IDEA, JetBrains
交通大學資訊工程學系 蔡文能 第 106頁
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!
Ready-4
交通大學資訊工程學系 蔡文能 第 107頁
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 Xerces2 Java Parser 2.4, The Apache XML
Project
交通大學資訊工程學系 蔡文能 第 108頁
Java Getting Started
Introduction to Java Programming
謝謝捧場http://www.csie.nctu.edu.tw/~tsaiwn/java/
蔡文能