Core Java
core4Operators
- Path
- pkg1core/core4Operators.java
- Package
- pkg1core
- Study order
- 3
- Run
- Single-file source launch
- Command
- java pkg1core/core4Operators.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core4Operators.java5 * --------------6 * Arithmetic, relational, logical, bitwise, assignment, and ternary operators.7 *8 * EXPLANATION:9 * - Integer division truncates; modulo gives the remainder.10 * - Logical && and || short-circuit (right side may not evaluate).11 * - Bitwise operators work on the binary representation (great for flags/masks).12 */13public class core4Operators {14 public static void main(String[] args) {15 int a = 17, b = 5;16 17 // Arithmetic18 System.out.println("a+b=" + (a + b) + " a-b=" + (a - b) + " a*b=" + (a * b));19 System.out.println("a/b=" + (a / b) + " (integer division truncates)");20 System.out.println("a%b=" + (a % b) + " (remainder)");21 22 // Relational23 System.out.println("a>b=" + (a > b) + " a==b=" + (a == b));24 25 // Logical with short-circuit demo26 System.out.println("short-circuit && : " + (b != 0 && a / b > 2));27 28 // Bitwise / shifts29 System.out.println("a & b = " + (a & b)); // AND30 System.out.println("a | b = " + (a | b)); // OR31 System.out.println("a ^ b = " + (a ^ b)); // XOR32 System.out.println("~a = " + (~a)); // NOT33 System.out.println("a<<1 = " + (a << 1) + " (multiply by 2)");34 System.out.println("a>>1 = " + (a >> 1) + " (divide by 2)");35 36 // Increment / decrement (pre vs post)37 int n = 5;38 System.out.println("n++ returns " + (n++) + ", then n=" + n);39 System.out.println("++n returns " + (++n) + ", n=" + n);40 41 // Compound assignment42 int total = 10;43 total += 5; total *= 2;44 System.out.println("compound assignment total=" + total);45 46 // Ternary47 String parity = (a % 2 == 0) ? "even" : "odd";48 System.out.println("a is " + parity);49 }50}