Home
01 Getting Started
02 Concepts
03 Variables & Data Types
a Variables & Data Types
b Text (Strings)
c Integers
d Floating Point Numbers
e Data Type - Primitives
f Converting Variables
g Casting
h Converting using Classes
i Arrays
04 Control Logic
05 Modifiers
06 GUI
07 Other Useful Classes
08 Handling Events
09 Handling Exceptions
10 Project 01 - Mortg Calc
11 More on Applets
12 Layout Manager
13 Project 02 - Calculator
14 Threads
15 Project 03 - Wake Up
16 File I/O
17 Project 04 - File I/O
Expanded Table of Contents
Debugging Hints
HTML Review
Download Samples
|
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
|
|