File tree 1 file changed +111
-0
lines changed
core-java-lang/src/test/java/com/baeldung/compoundoperators
1 file changed +111
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .baeldung .compoundoperators ;
2
+
3
+ import org .junit .Test ;
4
+
5
+ import static org .junit .Assert .assertEquals ;
6
+
7
+ public class CompoundOperatorsTest {
8
+
9
+ @ Test
10
+ public void whenAssignmentOperatorIsUsed_thenValueIsAssigned () {
11
+ int x = 5 ;
12
+
13
+ assertEquals (5 , x );
14
+ }
15
+
16
+ @ Test
17
+ public void whenCompoundAssignmentUsed_thenSameAsSimpleAssignment () {
18
+ int a = 3 , b = 3 , c = -2 ;
19
+ a = a * c ; // Simple assignment operator
20
+ b *= c ; // Compound assignment operator
21
+
22
+ assertEquals (a , b );
23
+ }
24
+
25
+ @ Test
26
+ public void whenAssignmentOperatorIsUsed_thenValueIsReturned () {
27
+ long x = 5 ;
28
+ long y = (x =3 );
29
+
30
+ assertEquals (3 , y );
31
+ assertEquals (y , x );
32
+ }
33
+
34
+ @ Test
35
+ public void whenCompoundOperatorsAreUsed_thenOperationsArePerformedAndAssigned () {
36
+ //Simple assignment
37
+ int x = 5 ; //x is 5
38
+
39
+ //Incrementation
40
+ x += 5 ; //x is 10
41
+ assertEquals (10 , x );
42
+
43
+ //Decrementation
44
+ x -= 2 ; //x is 8
45
+ assertEquals (8 , x );
46
+
47
+ //Multiplication
48
+ x *= 2 ; //x is 16
49
+ assertEquals (16 , x );
50
+
51
+ //Division
52
+ x /= 4 ; //x is 4
53
+ assertEquals (4 , x );
54
+
55
+ //Modulus
56
+ x %= 3 ; //x is 1
57
+ assertEquals (1 , x );
58
+
59
+
60
+ //Binary AND
61
+ x &= 4 ; //x is 0
62
+ assertEquals (0 , x );
63
+
64
+ //Binary exclusive OR
65
+ x ^= 4 ; //x is 4
66
+ assertEquals (4 , x );
67
+
68
+ //Binary inclusive OR
69
+ x |= 8 ; //x is 12
70
+ assertEquals (12 , x );
71
+
72
+
73
+ //Binary Left Shift
74
+ x <<= 2 ; //x is 48
75
+ assertEquals (48 , x );
76
+
77
+ //Binary Right Shift
78
+ x >>= 2 ; //x is 12
79
+ assertEquals (12 , x );
80
+
81
+ //Shift right zero fill
82
+ x >>>= 1 ; //x is 6
83
+ assertEquals (6 , x );
84
+ }
85
+
86
+ @ Test (expected = NullPointerException .class )
87
+ public void whenArrayIsNull_thenThrowNullException () {
88
+ int [] numbers = null ;
89
+
90
+ //Trying Incrementation
91
+ numbers [2 ] += 5 ;
92
+ }
93
+
94
+ @ Test (expected = ArrayIndexOutOfBoundsException .class )
95
+ public void whenArrayIndexNotCorrect_thenThrowArrayIndexException () {
96
+ int [] numbers = {0 , 1 };
97
+
98
+ //Trying Incrementation
99
+ numbers [2 ] += 5 ;
100
+ }
101
+
102
+ @ Test
103
+ public void whenArrayIndexIsCorrect_thenPerformOperation () {
104
+ int [] numbers = {0 , 1 };
105
+
106
+ //Incrementation
107
+ numbers [1 ] += 5 ;
108
+ assertEquals (6 , numbers [1 ]);
109
+ }
110
+
111
+ }
You can’t perform that action at this time.
0 commit comments