This post checks what you can and cannot store in a Java byte variable. In prog2, I tried to store -129 in a Java byte variable:
UBUNTU > cat prog2.java
public class prog2
{
public static void main (String args[])
{
// Declare a byte-size integer:
byte num1;
// Check what values it can store:
num1 = -129;
// Display the value:
System.out.println("num1 = " + num1);
}
}
UBUNTU >
... but I was unable to compile it:
UBUNTU > javac prog2.java
prog2.java:9: possible loss of precision
found : int
required: byte
num1 = -129;
^
1 error
UBUNTU >
In prog3, I tried to use a Java byte variable to store -128 and this worked:
public class prog3
{
public static void main (String args[])
{
// Declare a byte-size integer:
byte num1;
// Check what values it can store:
num1 = -128;
// Display the value:
System.out.println("num1 = " + num1);
}
}
UBUNTU > javac prog3.java
UBUNTU > java prog3
num1 = -128
UBUNTU >
In prog4, I tried to use a Java byte variable to store 127 and this worked too:
UBUNTU > cat prog4.java
public class prog4
{
public static void main (String args[])
{
// Declare a byte-size integer:
byte num1;
// Check what values it can store:
num1 = 127;
// Display the value:
System.out.println("num1 = " + num1);
}
}
UBUNTU > javac prog4.java
UBUNTU > java prog4
num1 = 127
UBUNTU >
public class prog4
{
public static void main (String args[])
{
// Declare a byte-size integer:
byte num1;
// Check what values it can store:
num1 = 127;
// Display the value:
System.out.println("num1 = " + num1);
}
}
UBUNTU > javac prog4.java
UBUNTU > java prog4
num1 = 127
UBUNTU >
In prog5, I tried to store 128 in a Java byte variable but this produced a compilation error:
UBUNTU > cat prog5.java
public class prog5
{
public static void main (String args[])
{
// Declare a byte-size integer:
byte num1;
// Check what values it can store:
num1 = 128;
// Display the value:
System.out.println("num1 = " + num1);
}
}
UBUNTU > javac prog5.java
prog5.java:9: possible loss of precision
found : int
required: byte
num1 = 128;
^
1 error
UBUNTU >
public class prog5
{
public static void main (String args[])
{
// Declare a byte-size integer:
byte num1;
// Check what values it can store:
num1 = 128;
// Display the value:
System.out.println("num1 = " + num1);
}
}
UBUNTU > javac prog5.java
prog5.java:9: possible loss of precision
found : int
required: byte
num1 = 128;
^
1 error
UBUNTU >
So it seems that Java byte variables can be used to store integers from -128 to +127, both inclusive.
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.