Thursday, 25 April 2013

Java Short Integers

These are 16-bit signed integers. They can store values between -32768 and +32767 both inclusive. If you try to assign numbers outside this range, you get a compilation error: 

UBUNTU > cat prog5.java
public class prog5
{
public static void main (String args[])
  {
  // Declare a short integer:
  short num1;

  // Try to assign some invalid values:
  num1 = -32769;
  num1 = 32768;
  }
}
UBUNTU > javac prog5.java
prog5.java:9: possible loss of precision
found   : int
required: short
  num1 = -32769;
          ^
prog5.java:10: possible loss of precision
found   : int
required: short
  num1 = 32768;
         ^
2 errors
UBUNTU >

...but numbers within the range are accepted:

UBUNTU > cat prog6.java
public class prog6
{
public static void main (String args[])
  {
  // Declare a short integer:
  short num1;

  // Assign the minimum valid value:
  num1 = -32768;

  // Display the value:
  System.out.println("num1 = " + num1);

  // Assign the maximum valid value:
  num1 = 32767;

  // Display the value:
  System.out.println("num1 = " + num1);
  }
}
UBUNTU > javac prog6.java
UBUNTU > java prog6
num1 = -32768
num1 = 32767
UBUNTU >


If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.