Java Reference
In-Depth Information
In this case,
i
is incremented by
1
, then the
old
value of
i
is used in the multiplication. So
newNum
becomes
100
. If
i++
is replaced by
++i
as follows,
int
i =
10
;
int
newNum =
10
* (++i);
Same effect as
i = i +
1
;
int
newNum =
10
* i;
System.out.print("i is " + i
+ ", newNum is " + newNum);
i is 11, newNum is 110
i
is incremented by
1
, and the new value of
i
is used in the multiplication. Thus
newNum
becomes
110
.
Here is another example:
double
x =
1.0
;
double
y =
5.0
;
double
z = x-- + (++y);
After all three lines are executed,
y
becomes
6.0
,
z
becomes
7.0
, and
x
becomes
0.0
.
Tip
Using increment and decrement operators makes expressions short, but it also
makes them complex and difficult to read. Avoid using these operators in expres-
sions that modify multiple variables or the same variable multiple times, such as this
one:
int k = ++i + i
.
2.25
✓
✓
Which of these statements are true?
Check
Point
a. Any expression can be used as a statement.
b. The expression
x++
can be used as a statement.
c. The statement
x = x + 5
is also an expression.
d. The statement
x = y = x = 0
is illegal.
2.26
Show the output of the following code:
int
a =
6
;
int
b = a++;
System.out.println(a);
System.out.println(b);
a =
6
;
b = ++a;
System.out.println(a);
System.out.println(b);
Floating-point numbers can be converted into integers using explicit casting.
Can you perform binary operations with two operands of different types? Yes. If an integer
and a floating-point number are involved in a binary operation, Java automatically converts
the integer to a floating-point value. So,
3 * 4.5
is same as
3.0 * 4.5
.
Key
Point
Search WWH ::
Custom Search