What is the output for the below code?
public class Test{
public static void main(String[] args){
byte b = 6;
b+=8;
System.out.println(b);
b = b+7;
System.out.println(b);
}
}
public class Test{
public static void main(String[] args){
byte b = 6;
b+=8;
System.out.println(b);
b = b+7;
System.out.println(b);
}
}
A. 14 21
B. 14 13
C. Compilation fails with an error at line 6
D. Compilation fails with an error at line 4
E. None of these
Answer: Option C
Solution(By Examveda Team)
int or smaller expressions always resulting in an int. So compiler complain about Type mismatch: cannot convert from int to byte for b = b+7; But b += 7; // No problem because +=, -=, *=, and /= will all put in an implicit cast. b += 7 is same as b = (byte)b+7 so compiler not complain.
Related Questions on Data Types and Variables
What is the maximum value that can be stored in a byte variable in Java?
A. 127
B. 255
C. 32767
D. 64
What is the default value of an int variable in Java if it's not explicitly initialized?
A. 0
B. 1
C. -1
D. Null
Which of the following is not a valid identifier for a Java variable?
A. my_var
B. _myVar
C. 3rdVar
D. $var
Join The Discussion