Java examples for Language Basics:Operator
Operators | Description | Type | Usage | Result |
---|---|---|---|---|
+ | Addition | Binary | 2 + 5 | 7 |
- | Subtraction | Binary | 5 - 2 | 3 |
+ | Unary plus | Unary | +5 | Positive five. Same as 5 |
- | Unary minus | Unary | -5 | Negative of five |
* | Multiplication | Binary | 5 * 3 | 15 |
/ | Division | Binary | 5 / 2 | 2 |
% | Modulus | Binary | 5 % 3 | 2 |
++ | Increment | Unary | num++ | Evaluates to the value of num, increments num by 1. |
-- | Decrement | Unary | num-- | Evaluates to the value of num, decrements num by 1. |
+= | Arithmetic compound-assignment | Binary | num += 5 | Adds 5 to the value of num and assigns the result to num. |
-= | Arithmetic compound assignment | Binary | num -= 3 | Subtracts 3 from the value of num and assigns the result to num. |
*= | Arithmetic compound assignment | Binary | num *= 15 | Multiplies 15 to the value of num and assigns the result to num. |
/= | Arithmetic compound assignment | Binary | num /= 5 | Divides the value of num by 5 and assigns the result to num. |
%= | Arithmetic compound assignment | Binary | num %= 5 | Calculates the remainder of num divided by 5 and assigns the result to num. |
public class Main { public static void main(String[] args) { int i = 110;// w w w .j a v a 2s .com float f = 120.2F; byte b = 5; String str = "Hello"; boolean b1 = true; i += 10; // Assigns 120 to i i -= 15; // Assigns 95 to i. Assuming i was 110 i *= 2; // Assigns 220 to i. Assuming i was 110 i /= 2; // Assigns 55 to i. Assuming i was 110 i /= 0; // A runtime error . Division by zero error f /= 0.0; // Assigns Float.POSITIVE_INFINITY to f i %= 3; // Assigns 2 to i. Assuming i is 110 str += " How are you?"; // Assigns "Hello How are you?" to str str += f; // Assigns "Hello120.2" to str. Assuming str was "Hello" b += f; // Assigns 125 to b. Assuming b was 5, f was 120.2 str += b1; // Assigns "Hellotrue" to str. Assuming str was "Hello" } }