運算子 | 功能 | 範例 |
---|---|---|
+ | 加 | a + b |
- | 減 | a - b |
* | 乘 | a * b |
/ | 除 | a / b |
% | 取餘數 | a % b |
基本資料型態 (primitive data type) 中的算術型態都可以做算術運算,以下為整數型態 (integer type) 做算術運算的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class ArithIntDemo { public static void main(String[] args) { int a, b, c; a = 8 ; b = 3 ; c = a + b; System.out.println( "a + b = " + c); c = a - b; System.out.println( "a - b = " + c); c = a * b; System.out.println( "a * b = " + c); c = a / b; System.out.println( "a / b = " + c); c = a % b; System.out.println( "a % b = " + c); } } /* 《程式語言教學誌》的範例程式 檔名:ArithIntDemo.java 功能:示範算術運算子的使用 作者:張凱慶 時間:西元 2010 年 10 月 */ |
編譯後執行,結果如下

注意程式的第 16 行
16 | c = a / b; |
由於是利用整數型態進行計算,所以得到的結果,程式印出的第 4 行也會是整數,這被稱為整數除法 (integer division) 。
以下為浮點數型態 (floating-point type) 做算術運算的例子,請留意,浮點數型態不能做取餘數的計算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class ArithFloatDemo { public static void main(String[] args) { double a, b, c; a = 8.3; b = 2.2; c = a + b; System.out.println( "a + b = " + c); c = a - b; System.out.println( "a - b = " + c); c = a * b; System.out.println( "a * b = " + c); c = a / b; System.out.println( "a / b = " + c); c = a % b; System.out.println( "a % b = " + c); } } /* 《程式語言教學誌》的範例程式 檔名:ArithFloatDemo.java 功能:示範算術運算子的使用 作者:張凱慶 時間:西元 2010 年 10 月 */ |
編譯後執行,結果如下

Java 的物件導向 (object-oriended) 的程式設計模式可以使運算子多載 (operator overloading) 。這是說相同的運算子在不同資料型態可以設定成不同的用途,例如,加法運算子 (additive operator) 在字串用於字串的連結 (concatenation) ,如下範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class ArithStringDemo { public static void main(String[] args) { String a = "Hello" ; String b = "world" ; String c = "!" ; String d = " " ; String e; e = a + b; System.out.println(e); e = a + d + b; System.out.println(e); e = a + d + b + c; System.out.println(e); } } /* 《程式語言教學誌》的範例程式 檔名:ArithStingDemo.java 功能:示範算術運算子的多載 作者:張凱慶 時間:西元 2010 年 10 月 */ |
編譯後執行,結果如下

中英文術語對照 | |
---|---|
算術運算 | arithmetic operation |
運算元 | operand |
算術運算子 | arithmetic operator |
基本資料型態 | primitive data type |
整數型態 | integer type |
整數除法 | integer division |
浮點數型態 | floating-point type |
物件導向 | object-oriended |
運算子多載 | operator overloading |
加法運算子 | additive operator |
連結 | concatenation |
參考資料
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html
沒有留言:
張貼留言