4 examples of using Java basic operator

1. Basic Operators

public class Arithmetic {
	public static void main(String args[]) {
		int a = 5, b = 2;
		int sum = a + b;
		int sub = a - b;
		int mul = a * b;
		float div = a / b;
		int mod = a % b;
		a++;
		b--;

		System.out.println("a + b=" + sum);
		System.out.println("a - b=" + sub);
		System.out.println("a * b=" + mul);
		System.out.println("a / b=" + div);
		System.out.println("a % b=" + mod);
		System.out.println("Unary incremental operation of a = " + a);
		System.out.println("Unary Reduction Operation of b = " + b);
	}
}
a + b=7
a - b=3
a * b=10
a / b=2.0
a % b=1
Unary incremental operation of a = 6
Unary Reduction Operation of b = 1
Result

2. Logical and Bitwise Operators

class Bitwise {
	public static void main(String args[]) {
		int a = 2;
		int b = 5;
		int c = a | b;
		int d = a & b;
		int e = a ^ b;
		int i;
		int j;
		i = a << 2;
		j = b >> 2;

		System.out.println("               a = " + a);
		System.out.println("               b = " + b);
		System.out.println("           a | b = " + c);
		System.out.println("           a & b = " + d);
		System.out.println("           a ^ b = " + e);
		System.out.println("          a << 2 = " + i);
		System.out.println("          b >> 2 = " + j);
	}
}
               a = 2
               b = 5
           a | b = 7
           a & b = 0
           a ^ b = 7
          a << 2 = 8
          b >> 2 = 1
Result

3. Assignment Operator

class BitEquals {
	public static void main(String args[]) {
		int a = 10;
		int b1 = 5;
		int b2 = 5;
		int b3 = 5;

		System.out.println("a = " + a);

		a += 4;
		System.out.println("a += result of 4 : " + a);

		a -= 4;
		System.out.println("a -= result of 4 : " + a);

		a *= 4;
		System.out.println("a *= result of 4 : " + a);

		a /= 4;
		System.out.println("a /= result of 4 : " + a);

		a %= 4;
		System.out.println("a %= result of 4 : " + a);

		a |= 4;
		System.out.println("a |= result of 4 : " + a);

		System.out.println("b1 = " + b1);
		System.out.println("b2 = " + b2);
		System.out.println("b3 = " + b3);

		b1 >>= 1;
		b2 <<= 1;
		b3 >>>= 1;
		System.out.println("b1 >>= result of 1 : " + b1);
		System.out.println("b2 <<= result of 1 : " + b2);
		System.out.println("b3 >>= result of 1 : " + b3);
	}
}
a = 10
a += result of 4 : 14
a -= result of 4 : 10
a *= result of 4 : 40
a /= result of 4 : 10
a %= result of 4 : 2
a |= result of 4 : 6
b1 = 5
b2 = 5
b3 = 5
b1 >>= result of 1 : 2
b2 <<= result of 1 : 10
b3 >>= result of 1 : 2
Result

4. Ternary operator

class TernaryDemo {
	public static void main(String args[]) {
		int i = 10;
		System.out.print("The value of the integer variable i is " + i + "and is ");
		String str =| (i % 2 == 0) ? "event" : "odd";
		System.out.print(str);
	}
}
The value of the integer variable i is 10 and is even
Result

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post