• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Rule for Numeric Type Promotion

 
Ranch Hand
Posts: 149
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rule 3 of  numeric promotion states:


Smaller data types, namely, byte, short, and char, are first promoted to int any time
they’re used with a Java binary arithmetic operator with a variable (as opposed to a
value), even if neither of the operands is int.

Part in brackets confuses me: (as opposed to a value),

What happens in terms of promotion in following examples:

char c1 = 'a';
char c2 = 'b';

int i1 = c1 + c2; //Here c1 and c2 are promoted to ints?
char c3 = c1 + c2; //How about here?

int i2 = 'a' + 'b'; //There is no promotion?
char c4 = c1 + c2;   //How about here?
 
Ranch Hand
Posts: 30
Python Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What I found for c3 and c4 that require to use char values, but c1 and c2 are considered int, but... what about to use Strings?
 
Sheriff
Posts: 9709
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

int i1 = c1 + c2; //Here c1 and c2 are promoted to ints?
char c3 = c1 + c2; //How about here?


You are right, c1 and c2 will be promoted to int, that's why the 2nd line won't compile.

int i2 = 'a' + 'b'; //There is no promotion?
char c4 = c1 + c2;   //How about here?


Here I'm assuming you wanted to write char ch4 = 'a' + 'b'; which does compile i.e. the literal values are not promoted to int.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic