numeric promotion

Oracle Certified Foundations Associate Java Certification Questions and Discussion

Moderator: admin

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

numeric promotion

Post by nick12345 »


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;

Code: Select all

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

Site Admin
Posts: 10023
Joined: Fri Sep 10, 2010 9:26 pm

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 (79.51 KiB) Viewed 4836 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

Re: numeric promotion

Post by hakim homsy »


Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests