Learning Java
Custom Search

Previous Next

Working With Numbers - Integers

There are multiple ways of representing numbers.   Integers, which are whole numbers, can be represented by the following types:

    byte    8 bits - values -128 to 127
    short 16 bits - values -32,768 to 32,767
    int     32 bits - values -2,147,483,648 to 2,147,483,647
    long   64 bits - values -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

When representing the literal value of a long integer, end the number in "L" or "l" (upper or lower case).

    long val = 3500L;    or    long val = 3500l;

In our example below, we define 4 different types of integers but we assign a value to them greater than what they can hold.

class IntegerTest {
   public static void main(String args[]) {
      byte b1 = 128;
      short s1 = 32768;
      int i1 = 2147483648;
      long l1 = 9223372036854775808L;

      System.out.println
	    ("b1=" + b1 + "  s1=" + s1 + "  i1=" + i1 + "  l1=" + l1);
   }
} 

The above won't compile. It complains that int i1 and long l1 are too large. It has not checked byte b1 and short s1. We make the correction to int i1 and long l1.

    int i1 = 2147483647;
    long l1 = 9223372036854775807L;

Now that the int and long values have been fixed, it pays attention to the byte and short values. It tells us that there is a possible loss of precision. We correct these values.

    byte b1 = 127;
    short s1 = 32767;

This time, we were able to complete the compilation successfully and then run our application.

 

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved