πŸ“Š JAVA
Q. What is the output for the below code ?
Code:
1. public class Test{
2.       public static void main(String[] args){
3.             byte b = 6;
4.             b+=8;
5.             System.out.println(b);
6.             b = b+7;
7.             System.out.println(b);
8.       }
9. }
  • (A) 14 21
  • (B) 14 13
  • (C) Compilation fails with an error at line 6
  • (D) Compilation fails with an error at line 4
πŸ’¬ Discuss
βœ… Correct Answer: (C) Compilation fails with an error at line 6

Explanation: 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.

Explanation by: Jatin Dubey
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.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
276
Total Visits
πŸ“½οΈ
4 y ago
Published
πŸŽ–οΈ
Jatin Dubey
Publisher
πŸ“ˆ
81%
Success Rate