它们用于对原始数据类型执行简单的算术运算。
// Java program to illustrate // arithmetic operators public class operators { public static void main(String[] args) { int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30; String x = "Thank", y = "You"; // + and - operator System.out.println("a + b = "+(a + b)); System.out.println("a - b = "+(a - b)); // + operator if used with strings // concatenates the given strings. System.out.println("x + y = "+x + y); // * and / operator System.out.println("a * b = "+(a * b)); System.out.println("a / b = "+(a / b)); // modulo operator gives remainder // on dividing first operand with second System.out.println("a % b = "+(a % b)); // if denominator is 0 in division // then Arithmetic exception is thrown. // uncommenting below line would throw // an exception // System.out.println(a/c); } }
输出:
a + b = 30 ab = 10 x + y = ThankYou a * b = 200 a / b = 2 a%b = 0
可以观察下面的一段代码,和输出的结果:
public class Geeksforgeeks { public static void main(String[] args) { System.out.println(2+0+1+6+"GeeksforGeeks"); System.out.println("GeeksforGeeks"+2+0+1+6); System.out.println(2+0+1+5+"GeeksforGeeks"+2+0+1+6); System.out.println(2+0+1+5+"GeeksforGeeks"+(2+0+1+6)); } }
输出是
9GeeksforGeeks GeeksforGeeks2016 8GeeksforGeeks2016 8GeeksforGeeks9
可以思考一下,解析答案在这篇文章:Java中的加法和连接