Q1. Write down the output ofthefollowing: a) int a = 10: System.out.println(a++ ): System.out.println(++a J;a+=2; System.out.println(a): b) System.out.println((int)3.14);
Answers
Question:-
Write down the output of the following:-
a) int a = 10;
System.out.println(a++);
System.out.println(++a);
System.out.println(a);
b) System.out.println((int)3.14));
Solution:-
a) Output :
10
12
12
b) Output :
3
Reason:-
a)
int a = 10
= Variable a has an assigned value 10.
a++
= This is a postfix increment. The rule of postfix increment is to first use , then increment.
So, the value of a++ remains same due to the rule.
//Now the value of a is 11 because of postfix law i.e., first use then increment. So the value of a++ will be 10 and after that, the current value of a will be incremented by 1 .
++a
= This is a prefix increment. The rule of prefix increment is to first increment then use.
So, the value of ++a will be 12.
//Now the value of a is 12.
a
= 12
b)
(int) 3.14
= We can see that the value has a decimal point i.e., it's data type is double data type.
This is a explicit type conversion.
So, when converting a double data type to int data type using explicit conversion , the output will be in the assigned data type.
Syntax:-
(data-type) expression
For example :-
double x = 3.14;
int y ;
y = (int) x;
Output : 3