Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009.

Similar presentations


Presentation on theme: "1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009."— Presentation transcript:

1

2 1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009

3 2 Basic form of a Java program 每一個 Java 程式都是由一個或更多個 Java 類別 (class) 所組成. 語法 (Syntax) : public class ClassName{ }

4 3 Methods 每一個 Java 類別 (class) 都有一個或更多個方 法 (method). 一個方法 (method) 是由一行行的指令 ( instruction) 所組成,這些指令會依序被執行 每一個 Java 程式都必須包含一個 main 方法 main 方法是第一個會被執行的方法 main 方法可以在呼叫其他的方法來執行整個程 式的某部份工作

5 4 Example : 輸出執行結果到螢幕上 // 利用 print, println 做輸出 public class FirstExample{ public static void main(String[] args){ System.out.print(" 我最喜歡的學科是 "); System.out.println(" 代數 "); } print 跟 println 是 System.out 這個 class 中的一個 method. System.out 是已經幫我們寫好的一 個用來輸出的 class.

6 Variable Declaration 在 Java 程式中如果要使用變數,必須先針對該變數進 行下列 2 項設定工作:指定變數的「名稱」 (Identifier) 宣告變數的「型態」 (Data Type) : Examples: /* Creates an integer variable */ int number; /* Creates a double variable */ double price; /* Creates a character variable */ char letter; Data typeidentifier Semi-colon

7 6 建立新的變數名稱時要遵照下列的規則: 一般而言,我們會使用英文字母、阿拉伯數字、底線 連接、 $ 等符號做為變數名稱 變數名稱並沒有長度的限制 Java 既有的關鍵字 (keyword) 不能做為變數名稱(例 如最常見的 2 個關鍵字 main 和 class )。 變數名稱不能用阿拉伯數字做為開頭。 英文字母的大小寫有區別 Variable Declaration

8 7 變數可以用來「存放」特定的文字或數字,這些文字 或數字有下列幾種不同的資料型態 (data type) ,下列 是 Java 的變數可以使用的基本資料型態: boolean char byte short int long float double Variable Declaration

9 Memory Concepts 變數名稱相對應於記憶體中的一個位置. 每個變數會有一個名稱、一個資料型別及一個變數值. 變數一經宣告之後,就可以指定 (assignment) 特定的 內容給變數,也就是讓變數真正「記住」您所指定的 內容。實際上指定內容給變數時,必須使用「 = 」。 int num; num = 3; 或 int num = 3; 第一次指定資料給變數的動作,稱為變數的初始化 (initialization)

10 Assignment Operator = (assignment operator) 這不是 “ 等於 ” 的意思,是把等號右邊的值指定給左 邊變數 例如 : int x, y, z; x = 5; y = 10; z = x + y; 這裡 x, y 被初始化成 5 跟 10 ,相加後的值儲存在變 數 z 中

11 Assignment & Basic Arithmetic /* 一個使用整數變數的例子 */ public class Sample { public static void main(String args[]) { int x, y, z; x = 5; y = 10; z = x + y; System.out.println (“x: “ + x); System.out.println (“y: “ + y); System.out.println (“z: “ + z); } // end method main } // end class Sample

12 Printing Variables 輸出變數的值時, 跟輸出字串 (String) 一樣使用 System.out.print 或 System.out.println System.out.print (x); System.out.println (x); System.out.println ("x: " + x); Here the “addition” that is performed is string concatenation. 這個加號所做的事,實 際上是字串的相連接 !


Download ppt "1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009."

Similar presentations


Ads by Google