numeric promotion

Oracle Certified Foundations Associate Java Certification Questions and Discussion
1Z0-811

Moderator: admin

Post Reply
nick12345
Posts: 17
Joined: Fri Aug 13, 2021 12:43 pm
Contact:

numeric promotion

Post by nick12345 »

Hello,

I have a question about this code example:

Why do we have a compiler time error?
Casting comes befor + operator, so I dont' understand why do we have int now.

Code: Select all

	short a = 1;
	short b = 2;
	short c = (short)a + (short)b;
I know, correct will be

Code: Select all

int c = a + b;
or

Code: Select all

short c = (short) ( a+b )
due to numeric promotion;

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: numeric promotion

Post by admin »

Good question. That is because a result of a binary numeric operation is always at least as large as an int. So, even though you have cast a and b to short, the result of the plus operator is still an int, which can't be assigned to a short without a cast. This is explained in detail in JFC JA Fundamentals study guide by Hanumant Deshmukh on page 123.
test.png
test.png (79.51 KiB) Viewed 4903 times
If you like our products and services, please help us by posting your review here.

hakim homsy
Posts: 2
Joined: Wed Sep 15, 2021 10:20 am
Contact:

Re: numeric promotion

Post by hakim homsy »

Thanks

Post Reply

Who is online

Users browsing this forum: No registered users and 15 guests