Results 1 to 2 of 2
  1. #1
    mljrg is offline Member
    Join Date
    Aug 2010
    Posts
    1
    Rep Power
    0

    Default Character arithmetic issues

    Hello,

    the following puzzles me :confused:

    Does someone know why the third line is flagged with an error ?

    char c1 = 'a' + 1; // ok
    int v = 1;
    char c2 = 'a' + v; // error "Type mismatch: cannot convert from int to char" !?!?

    Thanks
    Mário
    PS: I'm using Java 1.6

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,433
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by mljrg View Post
    Hello,

    the following puzzles me :confused:

    Does someone know why the third line is flagged with an error ?

    char c1 = 'a' + 1; // ok
    int v = 1;
    char c2 = 'a' + v; // error "Type mismatch: cannot convert from int to char" !?!?

    Thanks
    Mário
    PS: I'm using Java 1.6
    The compiler can only do 'constant folding' i.e. it can do calcualations on expressions that consists of constant operands only. Your first expression is such an expression and the compiler 'knows' that 'a'+1 == 'b' which fits in a character. The third expression isn't a constant expression so the compiler converts the single constant 'a' to an int, generates code for the addition operator and assumes that the result is also of type int. The result might not fit in a char so the compiler complains about it.

    kind regards,

    Jos

Similar Threads

  1. Polynomials Arithmetic
    By thisisIT in forum New To Java
    Replies: 3
    Last Post: 03-09-2010, 01:27 PM
  2. Arithmetic Stacks
    By unc123w in forum New To Java
    Replies: 22
    Last Post: 10-21-2008, 08:24 PM
  3. reading text character by character
    By bugger in forum New To Java
    Replies: 2
    Last Post: 11-09-2007, 08:54 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •