There are 4 Java primitives dealing with integer data. The difference is the number of bytes: 1, 2, 4 or 8. The number of bits is the number of bytes multiplied by 8-bits.
byte is 8-bits and can represent a number between -128 to +127. If we try to represent 128, which is out of range, it will be seen as -128.
// *** 1. Start (8-bits, -128 to +127) byte b1 = 5; byte b2 = -5; byte b3 = (byte)128; System.out.println("b3 = " + b3); // *** 1. End
short is 16-bits and can represent a number between -32,768 to +32,767. Again, we can see that representing 32,768, which is out-of-range, is seen as -32,768.
// *** 2. Start (16-bits, -32768 to 32767) short s1 = 5_000; short s2 = -5_000; short s3 = (short)32768; System.out.println("s3 = " + s3); // *** 2. End
int is 32-bits and can represent a number between -2^31 to +2^31-1. Any underscores in numbers are ignored.
// *** 3. Start (32-bits, -2,147,483,648 to // *** +2,147,483,647) int i1 = 5_000_000; int i2 = -5_000_000; int i3 = 2_147_483_647 + 1; System.out.println("i3 = " + i3); // *** 3. End
long is 64-bits and can represent a number between -2^63 to +2^63-1. To represent a large number you have to put L at end of number, since the default is integer with a lower range. You can also use lower-case letter l but it looks too much like the number 1.
// *** 4. Start (64-bits) // *** (From -9223372036854775808 to // *** +9223372036854775807) long l1 = 50_000_000_000L; long l2 = 50000000000L; System.out.println("l2-l1 = " + (l2-l1)); // *** 4. End
package com.javaAndroid.ex3; public class Ex3 { public static void main(String[] args) { // *** 1. Start (8-bits, -128 to +127) byte b1 = 5; byte b2 = -5; byte b3 = (byte)128; System.out.println("b3 = " + b3); // *** 1. End // *** 2. Start (16-bits, -32768 to 32767) short s1 = 5_000; short s2 = -5_000; short s3 = (short)32768; System.out.println("s3 = " + s3); // *** 2. End // *** 3. Start (32-bits, -2,147,483,648 to // *** +2,147,483,647) int i1 = 5_000_000; int i2 = -5_000_000; int i3 = 2_147_483_647 + 1; System.out.println("i3 = " + i3); // *** 3. End // *** 4. Start (64-bits) // *** (From -9223372036854775808 to // *** +9223372036854775807) long l1 = 50_000_000_000L; long l2 = 50000000000L; System.out.println("l2-l1 = " + (l2-l1)); // *** 4. End } }
No comments:
Post a Comment