In java if “char c = 'a' ” why does “c = c + 1” not compile?











up vote
2
down vote

favorite












I tried to compile the following code:



public static void main(String args){
for (char c = 'a'; c <='z'; c = c + 1) {
System.out.println(c);
}
}


When I try to compile, it throws:




Error:(5, 41) java: incompatible types: possible lossy conversion from
int to char




The thing is, it does work if I write c = (char)(c + 1), c += 1 or c++.



I checked and the compiler throws a similar error when I try char c = Character.MAX_VALUE + 1; but I see no way that the value of 'c' can pass 'char' type maximum in the original function.










share|improve this question




























    up vote
    2
    down vote

    favorite












    I tried to compile the following code:



    public static void main(String args){
    for (char c = 'a'; c <='z'; c = c + 1) {
    System.out.println(c);
    }
    }


    When I try to compile, it throws:




    Error:(5, 41) java: incompatible types: possible lossy conversion from
    int to char




    The thing is, it does work if I write c = (char)(c + 1), c += 1 or c++.



    I checked and the compiler throws a similar error when I try char c = Character.MAX_VALUE + 1; but I see no way that the value of 'c' can pass 'char' type maximum in the original function.










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I tried to compile the following code:



      public static void main(String args){
      for (char c = 'a'; c <='z'; c = c + 1) {
      System.out.println(c);
      }
      }


      When I try to compile, it throws:




      Error:(5, 41) java: incompatible types: possible lossy conversion from
      int to char




      The thing is, it does work if I write c = (char)(c + 1), c += 1 or c++.



      I checked and the compiler throws a similar error when I try char c = Character.MAX_VALUE + 1; but I see no way that the value of 'c' can pass 'char' type maximum in the original function.










      share|improve this question















      I tried to compile the following code:



      public static void main(String args){
      for (char c = 'a'; c <='z'; c = c + 1) {
      System.out.println(c);
      }
      }


      When I try to compile, it throws:




      Error:(5, 41) java: incompatible types: possible lossy conversion from
      int to char




      The thing is, it does work if I write c = (char)(c + 1), c += 1 or c++.



      I checked and the compiler throws a similar error when I try char c = Character.MAX_VALUE + 1; but I see no way that the value of 'c' can pass 'char' type maximum in the original function.







      java casting compiler-errors char primitive-types






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 at 11:01









      Mickael

      2,90521528




      2,90521528










      asked Nov 12 at 10:54









      רעי וייס ליפשיץ

      165




      165
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          8
          down vote



          accepted










          c + 1 is an int, as the operands undergo binary numeric promotion:





          • c is a char


          • 1 is an int


          so c has to be widened to int to make it compatible for addition; and the result of the expression is of type int.



          As for the things that "work":





          • c = (char)(c + 1) is explicitly casting the expression to char, so its value is compatible with the variable's type;


          • c += 1 is equivalent to c = (char) ((c) + (1)), so it's basically the same as the previous one.


          • c++ is of type char, so no cast is required.






          share|improve this answer























          • Good answer, only suggestion would be to mention why you can set an int to a char, but not a char to an int (possible lossy conversion due to assigning a bigger data type to a smaller data type)
            – Eamon Scullion
            Nov 12 at 11:06










          • First of all, thank you for the good answer. Second, if I understand correctly, that mean java takes 'c + 1' and instead of casting '1' to a char it casts 'c' to an int in order to add them together. Is this because converting an int to char has a potential of losing data?
            – רעי וייס ליפשיץ
            Nov 12 at 11:23






          • 1




            @רעיוייסליפשיץ yes. Note also that even if you add two chars together, they are still widened to int first. (Same is true of byte and short).
            – Andy Turner
            Nov 12 at 12:13










          • @רעיוייסליפשיץ "Note also that even if you add two chars together" so c + (char) 1 wouldn't have worked.
            – Andy Turner
            Nov 12 at 13:02












          • Thanks, but that leaves me with a question, why does char c = 97 + 1 work? wouldn't java see 97 + 1 as an int?
            – רעי וייס ליפשיץ
            Nov 12 at 22:41


















          up vote
          0
          down vote













          First you are declaring c as char than you are using it as an int






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53260641%2fin-java-if-char-c-a-why-does-c-c-1-not-compile%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            8
            down vote



            accepted










            c + 1 is an int, as the operands undergo binary numeric promotion:





            • c is a char


            • 1 is an int


            so c has to be widened to int to make it compatible for addition; and the result of the expression is of type int.



            As for the things that "work":





            • c = (char)(c + 1) is explicitly casting the expression to char, so its value is compatible with the variable's type;


            • c += 1 is equivalent to c = (char) ((c) + (1)), so it's basically the same as the previous one.


            • c++ is of type char, so no cast is required.






            share|improve this answer























            • Good answer, only suggestion would be to mention why you can set an int to a char, but not a char to an int (possible lossy conversion due to assigning a bigger data type to a smaller data type)
              – Eamon Scullion
              Nov 12 at 11:06










            • First of all, thank you for the good answer. Second, if I understand correctly, that mean java takes 'c + 1' and instead of casting '1' to a char it casts 'c' to an int in order to add them together. Is this because converting an int to char has a potential of losing data?
              – רעי וייס ליפשיץ
              Nov 12 at 11:23






            • 1




              @רעיוייסליפשיץ yes. Note also that even if you add two chars together, they are still widened to int first. (Same is true of byte and short).
              – Andy Turner
              Nov 12 at 12:13










            • @רעיוייסליפשיץ "Note also that even if you add two chars together" so c + (char) 1 wouldn't have worked.
              – Andy Turner
              Nov 12 at 13:02












            • Thanks, but that leaves me with a question, why does char c = 97 + 1 work? wouldn't java see 97 + 1 as an int?
              – רעי וייס ליפשיץ
              Nov 12 at 22:41















            up vote
            8
            down vote



            accepted










            c + 1 is an int, as the operands undergo binary numeric promotion:





            • c is a char


            • 1 is an int


            so c has to be widened to int to make it compatible for addition; and the result of the expression is of type int.



            As for the things that "work":





            • c = (char)(c + 1) is explicitly casting the expression to char, so its value is compatible with the variable's type;


            • c += 1 is equivalent to c = (char) ((c) + (1)), so it's basically the same as the previous one.


            • c++ is of type char, so no cast is required.






            share|improve this answer























            • Good answer, only suggestion would be to mention why you can set an int to a char, but not a char to an int (possible lossy conversion due to assigning a bigger data type to a smaller data type)
              – Eamon Scullion
              Nov 12 at 11:06










            • First of all, thank you for the good answer. Second, if I understand correctly, that mean java takes 'c + 1' and instead of casting '1' to a char it casts 'c' to an int in order to add them together. Is this because converting an int to char has a potential of losing data?
              – רעי וייס ליפשיץ
              Nov 12 at 11:23






            • 1




              @רעיוייסליפשיץ yes. Note also that even if you add two chars together, they are still widened to int first. (Same is true of byte and short).
              – Andy Turner
              Nov 12 at 12:13










            • @רעיוייסליפשיץ "Note also that even if you add two chars together" so c + (char) 1 wouldn't have worked.
              – Andy Turner
              Nov 12 at 13:02












            • Thanks, but that leaves me with a question, why does char c = 97 + 1 work? wouldn't java see 97 + 1 as an int?
              – רעי וייס ליפשיץ
              Nov 12 at 22:41













            up vote
            8
            down vote



            accepted







            up vote
            8
            down vote



            accepted






            c + 1 is an int, as the operands undergo binary numeric promotion:





            • c is a char


            • 1 is an int


            so c has to be widened to int to make it compatible for addition; and the result of the expression is of type int.



            As for the things that "work":





            • c = (char)(c + 1) is explicitly casting the expression to char, so its value is compatible with the variable's type;


            • c += 1 is equivalent to c = (char) ((c) + (1)), so it's basically the same as the previous one.


            • c++ is of type char, so no cast is required.






            share|improve this answer














            c + 1 is an int, as the operands undergo binary numeric promotion:





            • c is a char


            • 1 is an int


            so c has to be widened to int to make it compatible for addition; and the result of the expression is of type int.



            As for the things that "work":





            • c = (char)(c + 1) is explicitly casting the expression to char, so its value is compatible with the variable's type;


            • c += 1 is equivalent to c = (char) ((c) + (1)), so it's basically the same as the previous one.


            • c++ is of type char, so no cast is required.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 12 at 11:04

























            answered Nov 12 at 10:56









            Andy Turner

            80k879133




            80k879133












            • Good answer, only suggestion would be to mention why you can set an int to a char, but not a char to an int (possible lossy conversion due to assigning a bigger data type to a smaller data type)
              – Eamon Scullion
              Nov 12 at 11:06










            • First of all, thank you for the good answer. Second, if I understand correctly, that mean java takes 'c + 1' and instead of casting '1' to a char it casts 'c' to an int in order to add them together. Is this because converting an int to char has a potential of losing data?
              – רעי וייס ליפשיץ
              Nov 12 at 11:23






            • 1




              @רעיוייסליפשיץ yes. Note also that even if you add two chars together, they are still widened to int first. (Same is true of byte and short).
              – Andy Turner
              Nov 12 at 12:13










            • @רעיוייסליפשיץ "Note also that even if you add two chars together" so c + (char) 1 wouldn't have worked.
              – Andy Turner
              Nov 12 at 13:02












            • Thanks, but that leaves me with a question, why does char c = 97 + 1 work? wouldn't java see 97 + 1 as an int?
              – רעי וייס ליפשיץ
              Nov 12 at 22:41


















            • Good answer, only suggestion would be to mention why you can set an int to a char, but not a char to an int (possible lossy conversion due to assigning a bigger data type to a smaller data type)
              – Eamon Scullion
              Nov 12 at 11:06










            • First of all, thank you for the good answer. Second, if I understand correctly, that mean java takes 'c + 1' and instead of casting '1' to a char it casts 'c' to an int in order to add them together. Is this because converting an int to char has a potential of losing data?
              – רעי וייס ליפשיץ
              Nov 12 at 11:23






            • 1




              @רעיוייסליפשיץ yes. Note also that even if you add two chars together, they are still widened to int first. (Same is true of byte and short).
              – Andy Turner
              Nov 12 at 12:13










            • @רעיוייסליפשיץ "Note also that even if you add two chars together" so c + (char) 1 wouldn't have worked.
              – Andy Turner
              Nov 12 at 13:02












            • Thanks, but that leaves me with a question, why does char c = 97 + 1 work? wouldn't java see 97 + 1 as an int?
              – רעי וייס ליפשיץ
              Nov 12 at 22:41
















            Good answer, only suggestion would be to mention why you can set an int to a char, but not a char to an int (possible lossy conversion due to assigning a bigger data type to a smaller data type)
            – Eamon Scullion
            Nov 12 at 11:06




            Good answer, only suggestion would be to mention why you can set an int to a char, but not a char to an int (possible lossy conversion due to assigning a bigger data type to a smaller data type)
            – Eamon Scullion
            Nov 12 at 11:06












            First of all, thank you for the good answer. Second, if I understand correctly, that mean java takes 'c + 1' and instead of casting '1' to a char it casts 'c' to an int in order to add them together. Is this because converting an int to char has a potential of losing data?
            – רעי וייס ליפשיץ
            Nov 12 at 11:23




            First of all, thank you for the good answer. Second, if I understand correctly, that mean java takes 'c + 1' and instead of casting '1' to a char it casts 'c' to an int in order to add them together. Is this because converting an int to char has a potential of losing data?
            – רעי וייס ליפשיץ
            Nov 12 at 11:23




            1




            1




            @רעיוייסליפשיץ yes. Note also that even if you add two chars together, they are still widened to int first. (Same is true of byte and short).
            – Andy Turner
            Nov 12 at 12:13




            @רעיוייסליפשיץ yes. Note also that even if you add two chars together, they are still widened to int first. (Same is true of byte and short).
            – Andy Turner
            Nov 12 at 12:13












            @רעיוייסליפשיץ "Note also that even if you add two chars together" so c + (char) 1 wouldn't have worked.
            – Andy Turner
            Nov 12 at 13:02






            @רעיוייסליפשיץ "Note also that even if you add two chars together" so c + (char) 1 wouldn't have worked.
            – Andy Turner
            Nov 12 at 13:02














            Thanks, but that leaves me with a question, why does char c = 97 + 1 work? wouldn't java see 97 + 1 as an int?
            – רעי וייס ליפשיץ
            Nov 12 at 22:41




            Thanks, but that leaves me with a question, why does char c = 97 + 1 work? wouldn't java see 97 + 1 as an int?
            – רעי וייס ליפשיץ
            Nov 12 at 22:41












            up vote
            0
            down vote













            First you are declaring c as char than you are using it as an int






            share|improve this answer

























              up vote
              0
              down vote













              First you are declaring c as char than you are using it as an int






              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                First you are declaring c as char than you are using it as an int






                share|improve this answer












                First you are declaring c as char than you are using it as an int







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 12 at 10:57









                Brian

                527




                527






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53260641%2fin-java-if-char-c-a-why-does-c-c-1-not-compile%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python