Primitive VariablesS2C Home « Primitive Variables
So what is a variable? Well a variable allows us to store some information that we may want to manipulate or use. The variable is like a container where we put our information for use and retrieval.
Java comes with two types of variables to choose from, primitives and reference. In this lesson we look at the various primitive data types that are available in Java. We discuss Reference Variables in the Objects & Classes section.
The primitive specified determines which operations are allowed on it and thus operations valid for one primitive type may be invalid for another.
Variables in JavaTop
Java is a strongly typed language and as such cares about the type of the variables we declare. So what does this statement actually mean? Well whenever you declare a variable in Java, you have to give it a type, or the compiler complains when you come to compile your code. You also have to name the variable and there are rules on naming.

Before we get into coding some variables lets look at the various types of primitives and the rules associated with naming them.
Type | Meaning | Bit Width | Range |
---|---|---|---|
boolean and char | |||
boolean | true/false values | JVM specific | true or false |
char | Character | 16 | 0 to 65535 - ( |
signed numeric integers | |||
byte | 8-bit integer | 8 | -128 to 127 |
short | Short integer | 16 | -32,768 to 32,767 |
int | Integer | 32 | -2,147,483,648 to 2,147,483,647 |
long | Long integer | 64 | -9,233,372,036,854,775,808 to 9,233,372,036,854,775,807 |
signed floating point | |||
float | Single-precision float | 32 | varies |
double | Double-precision float | 64 | varies |
Naming Rules and KeywordsTop
These rules apply to all variables, as well as classes and methods (collectively known as identifiers)
- Must start with a letter, the underscore symbol (_) or the dollar sign ($). A name can't start with a number or any other symbol.
- You can use numbers after the first letter, you just can't start with it.
- You cannot use keywords or names recognized by the compiler. See the table below for the words you can't use.
Click a link in the table below to show lesson usage for any keyword you're interested in:
Keywords marked with an asterisk (*) are not used.
Although not a rule as such it's also important to know that identifiers are case-sensitive.
Naming Rules Test
Try this to test your knowledge of naming rules. We will go into the types as we go through the lesson but you should be able to pick out the invalidly named identifiers from the rules above.
Statement | Question | |
---|---|---|
boolean a = true; |
| This passes all the rules so is a valid identifier |
char 1char = 'O'; |
| Starts with a numeric so invalid |
char enum = 'a'; |
| Uses a reserved word so invalid |
int $num = true; |
| This passes all the rules so is a valid identifier |
long a123 = 234; |
| This passes all the rules so is a valid identifier |
short this = 2; |
| Uses a reserved word so invalid |
byte _aByte2 = 'a'; |
| This passes all the rules so is a valid identifier |
boolean &b = 'a'; |
| Doesnt start with letter, $ or _ so invalid |
The boolean
TypeTop
The boolean
type represents true and false values which are defined in java using the true
and false
reserved words. The
boolean type can be initialized using these values, control the flow of an if
statement and is returned from a relational operator. Lets write some
code to see this in action. With your text editor open, cut and paste the following code into it.
/*
Initialising and using booleans primitives
*/
public class BooleanType {
public static void main (String[] args) {
boolean a; // Not initialized
boolean b = true; // Initialized
a = false; // Initialized after creation
System.out.println("a is " + a);
System.out.println("b is " + b);
if (a) { System.out.println("a is executed"); } // a is false so will not execute
if (b) { System.out.println("b is executed"); } // b is true so will execute
// Relational operator output is a boolean
System.out.println("1 > 2? is " + (1 > 2));
System.out.println("2 > 1? is " + (2 > 1));
}
}
Click file from the toolbar and then click the save option.
In the tab at the top make sure you are pointing to the _Beginningjava folder we created in the last lesson.
In the File name: text area type BooleanType.java and then click the Save button and close the Notepad.

Compiling And Running Our Source File
Open your command line editor:
change to directory cd c:\_Beginningjava
compile BooleanType.java using the java compiler javac BooleanType.java
run BooleanType.class using the java intepreter java BooleanType

You should see 5 lines of output as shown in the screenshot. The first two output lines display the values we set for our variables. The interesting thing to
note here is the use of the +
symbol, which is used in java to concatenate strings aside from its mathematical uses. The third output line
shows the results of the second if
statement we coded. We will go into this statement in the Conditional Statements lesson for now it's enough to
know that statements contained within the curly bracers will execute when the expression being tested is true. The last two outputs test relational operators and output a boolean dependant upon the result.
The char
TypeTop
Most computer languages use the standard 8-bit ASCII character set which has a range of 0
to 127
to represent characters. In Java the
char
primitive type is an unsigned type in the range 0
to 65,536
and uses Unicode. Unicode defines a
character set that can represent any character found in any human language. The ASCII character set is a subset of Unicode and as such
ASCII characters are still valid in Java. With your text editor open, cut and paste the following code into it.
/*
Initialising and using char primitives
*/
public class CharType {
public static void main (String[] args) {
char charA = 'P'; // Initialized using value in single quotes
System.out.println("charA is " + charA);
charA -= 12; // We can subtract from the char type
System.out.println("charA is " + charA);
charA = 45; // We can assign an integer to the char type
System.out.println("charA is " + charA);
}
}
Save, compile and run the file in directory c:\_Beginningjava

You should see 3 lines of output as shown in the screenshot. The first output line displays the value 'P' that we assigned to our variable. The second output
line shows the result of subtracting 12 from our initial value. The third output line shows the result of assigning integer 45 to our variable. Because the
char
primitive type is an unsigned 16-bit type we can perform mathematics on this type as if it was an integer, remember though the range is
0
to 65,536
.
Signed Numeric Integer TypesTop
Java has 4 numeric integer types byte
, short
, int
and long
.
Type | Meaning | Bit Width | Range |
---|---|---|---|
byte | 8-bit integer | 8 | -128 to 127 |
short | Short integer | 16 | -32,768 to 32,767 |
int | Integer | 32 | -2,147,483,648 to 2,147,483,647 |
long | Long integer | 64 | -9,233,372,036,854,775,808 to 9,233,372,036,854,775,807 |
As you can see you have a choice of four different sized containers to store your integer values in. So using the correct integer type for your needs saves some bytes. You can assign one primitive integer type to another as long as the assignment is to a larger container. If you try to assign a larger integer type to a smaller the compiler throws an error and won't allow it. With your text editor open, cut and paste the following code into it.
/*
Initialising and using numeric integer primitives
*/
public class IntTypes {
public static void main (String[] args) {
byte aByte = 128;
System.out.println("aByte = " + aByte);
short aShort = 642;
System.out.println("aShort = " + aShort);
int anInt = 12;
System.out.println("anInt = " + anInt);
long aLong = 3672543567;
System.out.println("aLong = " + aLong);
aShort = anInt;
System.out.println("aShort = " + aShort);
aLong = aByte;
System.out.println("aLong = " + aLong);
}
}
Save and compile the file in directory c:\_Beginningjava

Ok the compile has failed with an error as shown in the screenshot and we get our first look at a compiler error. The reason for this is that when we pass a
literal value to a long we need to append l
or L
to it or the compiler inteprets it as an integer. Because an integer has a range of
-2,147,483,648
to 2,147,483,647
the number is out of range even though we passed it to a long
primitive type. We will go into literals later in this lesson for now lets correct our code and append an L
to it. I suggest always using an
uppercase L
when specifying a long literal as a lowercase l
looks a lot like the number 1
. So edit your code and add the
L
to the end of the number so you now have 3672543567L
.
Save and compile the file in directory c:\_Beginningjava

Ok the compile has failed again with two more errors as shown in the screenshot above. The first error is because we have given the variable aByte
a value of 128. The byte
type range is -128
to 127
so this is out of range. Change this to 127 to fix
this error. The second error happens because we are trying to put an int
into a short
.
Even though the value contained in the variable anInt
of 12
easily fits into the range of a short -32,768
to 32,767
the compiler just sees an int
trying to be squeezed into a short
and won't allow it. So let's change this to aByte
from
anInt
as follows aShort = aByte;
.
Save, compile and run the file in directory c:\_Beginningjava

Well we got there in the end and as you can see the Java compiler isn't always as intuitive as we would like. Sometimes the compiler points to the wrong line or points to a place above or below the error. With practice you get used to compiler errors and you will get plenty of that as you write your Java code :).
Numeric Integer Test
Try this to test your knowledge of numeric integer types. Read down the list and check those you think will compile. Treat the list as a sequence of statements.
Statement | Question | |
---|---|---|
int i; byte b = -12; short s = 123.45; long l = 12; i = l; b = -130; l = b; l = 12L; |
|
This will compile. This will compile. Will not compile (cannot put a double in an int). This will compile (treated as an int and in range). Will not compile (cannot put an int into a long). Will not compile (out of range). This will compile. This will compile. |
Signed Floating-Point TypesTop
Java has 2 floating-point types float
and double
.
Type | Meaning | Bit Width | Range |
---|---|---|---|
float | Single-precision float | 32 | varies |
double | Double-precision float | 64 | varies |
Floating-point types represent non-integer numbers that have a fractional component and come in two flavours as described in the table above. Floating-point
types default to the double
type unless we append an f
or F
when we initialize them. When this happens the compiler fails
as it thinks we passed a double
to a float
primitive.
/*
Initialising and using numeric floating-point primitives
*/
public class FloatTypes {
public static void main (String[] args) {
float aFloat = 12.34F;
System.out.println("aFloat = " + aFloat);
double aDouble = 642.2761;
System.out.println("aDouble = " + aDouble);
double bDouble = aFloat * aDouble; // Dynamically initialized at runtime from other variables
System.out.println("bDouble = " + bDouble);
}
}
Save, compile and run the file in directory c:\_Beginningjava

Above is the screenshot of running this code. Notice that the floating point doesn't display the F
its just our way of telling the compiler this
is a float
primitive. The other interesting point is variable bDouble
which is dynamically initialized at runtime from the other two variables
Java LiteralsTop
Java literals are values that are represented in their recognizable everyday form and we have been using them within our coding throughout the lessons so far. The table below gives examples of literals for each primitive type used in this lesson and introduces a few we haven't come across yet.
Type | Examples |
---|---|
boolean | |
boolean | true or false |
char | |
char | 16, 'G', 'a' (numeric or a single character enclosed in single quotes) |
signed integers | |
byte | Negative or positive integers in the range -128 to 127 |
short | Negative or positive integers in the range -32,768 to 32,767 |
int | Negative or positive integers in the range -2,147,483,648 to 2,147,483,647 |
long | Negative or positive integers in the range -9,233,372,036,854,775,808 to 9,233,372,036,854,775,807 Append a l or L to the number or it will be treated as type int .12l, -123456L |
signed floating point | |
float | Append a f or F to the number or it will be treated as type double .25.23f , -1234.56F |
double | 12.34 , -56.72456 |
hexadecimal constants | |
byte, short, int, long | Can be used with any integer type as long as it is in range for that type.0xF , 0xFA |
octal constants | |
byte, short, int, long | Can be used with any integer type as long as it is in range for that type.05 , 012 |
string literals | |
"hello", "welcome back" (enclosed in double quotes) The following are escape character constants that are required for rendering or printing and use the backslash symbol \ to signify the escape sequence.\' Escape a single quote\" Escape a double quote\\ Escape a backslash\b Escape a backspace\f Escape a form feed\n Escape a new line\r Escape a carriage return\t Escape a tab\ooo Escape an octal constant where ooo is the octal constant\uhhhh Escape a hexidecimal constant where hhhh is the hexidecimal constant |
Lesson 3 Complete
In this lesson we looked at the primitive variable data types available in java.
What's Next?
In the next lesson we look at method scope and what scope and its definition mean.