Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: help needed to know how the code is running

  1. #1
    Junior Member
    Join Date
    Jul 2012
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default help needed to know how the code is running

    class Char{
    public static void main (String a[])
    {
    char c1,c2,c3;
    c1=64;
    c2=187;
    //c3=64+187;
    System.out.println("The symbol is "+ (c1+c2));
    }
    }
    output 251

    class Char{
    public static void main (String a[])
    {
    char c1,c2,c3;
    c1=64;
    c2=187;
    c3=64+187;
    System.out.println("The symbol is "+ c3);
    }
    }
    output a symbol

    Why are the two outputs different plz explain i have[INDENT] written this code in notepad ++


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: help needed to know how the code is running

    In Java for an arithmetic expression involving two char variables, the operands are promoted to ints and the result is an int.

    Then, when you use println("whatever" + (c1+c2)) it prints the integer value of the sum of integer 64 and integer 187

    On the other hand...

    When you write char c3 = 64+187, it automatically converts the integer sum of 64 and 187 to a char and stores it in c3. Then when you use println("whatever" + c3) you get the Java char corresponding to the integer value 251 (shows up on my system as a lower-case Latin u with circumflex).

    The topic Numeric Promotions and its implications is spelled out in section 5.6 of the Java Language Specification. Maybe there is some information in whatever reference material you are learning Java from. (Class notes? Textbook? What?)

    Maybe you can play around with something like
    public class Z
    {
        public static void main(String [] args)
        {
            char c1, c2, c3, c4;
            c1 = 64;
            c2 = 187;
            c3 = 64 + 187;
            c4 = (char)(c1 + c2);// Cast needed to prevent compiler warning
     
            System.out.println("          c1  = " + c1);
            System.out.println("          c2  = " + c2);
            System.out.println("          c3  = " + c3);
            System.out.println("          c4  = " + c4);
            System.out.println();
     
            System.out.println("     (int)c1  = " + (int)c1);
            System.out.println("     (int)c2  = " + (int)c2);
            System.out.println("     (int)c3  = " + (int)c3);
            System.out.println("     (int)c4  = " + (int)c4);
            System.out.println();
     
            System.out.println("       c1+c2  = " + (c1+c2));
            System.out.println("(char)(c1+c2) = " + (char)(c1+c2));
        }
    }

    See if the output makes sense. If not, tell us what it printed and what you expected it to print and what you don't understand about the difference(s).

    Cheers!

    Z
    Last edited by Zaphod_b; July 16th, 2012 at 01:20 PM.

  3. The Following User Says Thank You to Zaphod_b For This Useful Post:

    Dark knight (July 19th, 2012)

  4. #3
    Junior Member
    Join Date
    Jul 2012
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: help needed to know how the code is running

    thanx Zaphod_b you were a great help i have been referring complete reference for java i read about type promotion and casting and now i understand it completely...

  5. #4
    Junior Member
    Join Date
    Jul 2012
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: help needed to know how the code is running

    class None{
    public static void main(String args[])
    {
    byte b =-2;
    b = (byte)(b>>>10);
    System.out.println("the value of b is"+b);// output -1
    }
    }

    I am not getting why this code is generating -1 ,as >>> this is an unsigned operator it should append zero at th higher priority bits kindly reply!!!1

  6. #5
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    980
    Thanks
    7
    Thanked 207 Times in 183 Posts

    Default Re: help needed to know how the code is running

    What has this got to do with the subject of this thread?

    kindly reply!!!1
    To avoid getting more !!!1 than kindness in your replies, please decide to which of your threads people should post. And leave a note in the other one redirecting them.

  7. #6
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: help needed to know how the code is running

    Quote Originally Posted by pbrockway2 View Post
    What has this got to do with the subject of this thread?
    Actually it is related because it concerns the effects of Numeric Promotions, and this question is a continuation of investigation of the concepts illustrated by the original post in this thread and by my previous response. The problem (from my point of view) is that the title of the thread is singularly uninformative.

    The other recent thread from this Poster has a similar title, but is about a completely different topic, namely, about using an int condition in an if() statement.

    To the Original Poster: Try to choose appropriate titles for your threads.

    To the Community: Sometimes when people start threads they don't know the exact terminology to make the titles something that is "textbook-precise." If I think I can help, I'll give it a shot. If others think that it's not worth their efforts to try to figure out where it's coming from and don't want to try, well, as my dear old Earthling-adoptive grannie used to say, "Chacun à son goût!" Actually, she used the cajun equivalent "A chacun son goût," but her snobbish son (my adoptive Uncle Whose Name Must Not Be Spoken) tried to refine it by using textbook French. But that's another story...


    Anyhow...
    Quote Originally Posted by Dark knight
    why this code is generating -1
    In the expression (byte)(b >>> 10), b is promoted to an int. The int is shifted right (with zeros shifted into the upper bits), and then you cast it to a byte (which merely chops off the upper 24 bits of the int. Since the eight lower bits are '1' the result is decimal -1.

    Here's an example, where I have separated out the conversion to byte. I lined up the bits of the byte variable below the place in the int variable where the byte got its value. I put everything in a loop so that we can see the results as it is shifted one bit at a time:
    public class z
    {
        public static void main(String [] args)
        {
            byte b =-2;
     
            for (int i = 0; i < 11; i++)
            {
                int intc = (b >>> i);
                byte bytec = (byte)intc; // Cast is necessary to make the compiler tolerate the loss of precision
                System.out.printf("i = %2d: Decimal value of intc  = %d\n", i, intc);// output -1
                System.out.printf("        Binary  value of intc  = %32s\n", binaryInt(intc));
                System.out.printf("        Binary  value of bytec = %32s\n", binaryByte(bytec));
                System.out.printf("        Decimal value of bytec = %d\n\n", bytec);// output -1
            }
        }
     
        // Convert a byte to a binary string with leading zeros
        static String binaryByte(byte x)
        {
     
            String str = "";
            for (int mask = 0x80; mask != 0; mask >>>= 1)
            {
                if ((mask & x) == 0) 
                {
                    str += '0';
                }
                else
                {
                    str += '1';
                }
            }
            return str;
        }
     
        // Convert an int to a binary string with leading zeros
        static String binaryInt(int x)
        {
     
            String str = "";
            for (int mask = 0x80000000; mask != 0; mask >>>= 1)
            {
                if ((mask & x) == 0) 
                {
                    str += '0';
                }
                else
                {
                    str += '1';
                }
            }
            return str;
        }
    }

    Output:
    i =  0: Decimal value of intc  = -2
            Binary  value of intc  = 11111111111111111111111111111110
            Binary  value of bytec =                         11111110
            Decimal value of bytec = -2
     
    i =  1: Decimal value of intc  = 2147483647
            Binary  value of intc  = 01111111111111111111111111111111
            Binary  value of bytec =                         11111111
            Decimal value of bytec = -1
     
    i =  2: Decimal value of intc  = 1073741823
            Binary  value of intc  = 00111111111111111111111111111111
            Binary  value of bytec =                         11111111
            Decimal value of bytec = -1
     
    i =  3: Decimal value of intc  = 536870911
            Binary  value of intc  = 00011111111111111111111111111111
            Binary  value of bytec =                         11111111
            Decimal value of bytec = -1
     
    i =  4: Decimal value of intc  = 268435455
            Binary  value of intc  = 00001111111111111111111111111111
            Binary  value of bytec =                         11111111
            Decimal value of bytec = -1
    .
    .
    .
    i = 10: Decimal value of intc  = 4194303
            Binary  value of intc  = 00000000001111111111111111111111
            Binary  value of bytec =                         11111111
            Decimal value of bytec = -1



    The bottom line for me is: If you have to use a cast, somewhere ("just to keep the compiler happy"), make absolutely sure that you understand the ramifications.


    Cheers!

    Z
    Last edited by Zaphod_b; July 19th, 2012 at 04:49 PM.

  8. The Following User Says Thank You to Zaphod_b For This Useful Post:

    Dark knight (July 20th, 2012)

  9. #7
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    980
    Thanks
    7
    Thanked 207 Times in 183 Posts

    Default Re: help needed to know how the code is running

    Thanks for alerting everyone to the accidental duplicate in the other post.

    What you're dealing with in the cast to byte is a so-called "narrowing primitive conversion" and is dealt with in JLS 5.1.3. (Casts in general are described at 5.6) This occurs after the unary numeric promotion you get as a result of using the >>> operator which had already been referred to.

    The mark of such narrowing conversions is that they can do real "damage" to the value, not just the amount of precision involved. In the case of int->byte the docs actually warn us "A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value".

    -----

    You actually had an example of another narrowing primitive conversion in the original post of this thread: "c3=64+187;" where c3 is of type char.

    The right hand side is a constant int expression. And when it gets assigned to a char variable a narrowing primitive conversion takes place. This only applies to constant expressions like "64+187", anything else requires a cast like that in #4 to byte. Either way though - cast (5.2) or assignment (5.6) - you get a potentially dangerous narrowing from int to something "smaller".

  10. #8
    Junior Member
    Join Date
    Jul 2012
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: help needed to know how the code is running

    thanx zaphod_b for the clarification i get it now and i will keep in mind the thread thinng....
    thanx pbrockway2 but i dont have JLS to refer with i am using complete reference for java should i switch over to JLS is it better

  11. #9
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    980
    Thanks
    7
    Thanked 207 Times in 183 Posts

    Default Re: help needed to know how the code is running

    The JLS is available online (like this forum). It is probably *not* better than a (good) book because of all the lawyerly twists and turns. But it *is* authoritative and, hence, a necessary complement to any other resources. For questions like this (when and how values get associated with different types) there is ultimately no other source of truth.

    Unlike Oracle's Tutorial which I link to because of the explanations and examples it gives, I would link to the JLS only because of the detail which it offers which would be tedious to repeat (and which is probably more than was asked about). If you are new to Java you should be aware of its existence and begin to get familiar with it, but should *not* be overwhelmed and feel that every last clause be understood at first reading.

  12. #10
    Member
    Join Date
    Jul 2012
    Posts
    90
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: help needed to know how the code is running

    Quote Originally Posted by Zaphod_b View Post
    [url=docs.oracle.com/javase/specs/jls/se5.0/jls3.pdf]
    This is a book for JAVA,isn't it?I want to learn JAVA,and the publisher of this book is well known to me.Take notice that i know C and C++ quite well.So it this book appropriate for me to read?Or is it too much for a BEGINNER² like me to study it?I have read only a small tutorial about JAVA on the net,but it was too brief i think.

    Comment : I know that is off topic but starting a new thread just about it i do not if it was going to be appropriate

Similar Threads

  1. [SOLVED] n00b having problems running code
    By cha0s619 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: November 10th, 2012, 04:31 PM
  2. Help needed with code
    By mmkmmk3 in forum What's Wrong With My Code?
    Replies: 19
    Last Post: July 31st, 2011, 12:27 AM
  3. Help needed with calculator code
    By andys in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 21st, 2011, 09:02 PM
  4. HELP! Gui is running fine, don't know exactly how to code.
    By cc11rocks in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 12th, 2011, 02:12 PM
  5. making my code a little better, if needed.
    By vendetta in forum Object Oriented Programming
    Replies: 4
    Last Post: February 11th, 2010, 03:40 AM