short variables


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: short variables

  1. #1
    Sharad Joshi Guest

    short variables


    I just wanted to share this interesting feature of Java compilers regarding
    the short variables. The following program snippet gives compiler error.
    See why ....

    public class XYZ {
    public static void main(String[] args)
    {
    short i = 10;
    short j = 20;
    short k = 0;
    k = i + j; // Here is the compiler error
    System.out.println("i=" + i + " j=" + j + " k=" + k);
    }
    }

    My answer will follow soon.

    Sharad Joshi

  2. #2
    Sharad Joshi Guest

    Re: short variables


    Although short variables are 16-bit long, the arithmetic on these short variables
    is still 32-bit ! That is why, the compiler error is generated. So, the code
    will work if the addition is casted to short.
    The code line where the error is generated can be rewritten as:
    k = (short) (i + j); // No errors
    Typecasting only i and/or j will not do, the sum has to be done.

    Sharad

    "Sharad Joshi" <hisharad@hotmail.com> wrote:
    >
    >I just wanted to share this interesting feature of Java compilers regarding
    >the short variables. The following program snippet gives compiler error.
    >See why ....
    >
    >public class XYZ {
    > public static void main(String[] args)
    > {
    > short i = 10;
    > short j = 20;
    > short k = 0;
    > k = i + j; // Here is the compiler error
    > System.out.println("i=" + i + " j=" + j + " k=" + k);
    > }
    >}
    >
    >My answer will follow soon.
    >
    >Sharad Joshi



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center