Primitive Variables Homepage  « Learn Java5 « 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 Javago to top of page Top

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.

type diagram

Before we get into coding some variables lets look at the various types of primitives and the rules associated with naming them.

Primitive Types
Type Description Bit Width Range
boolean and char
booleantrue/false valuesJVM specifictrue or false
charCharacter160  to  65535 - ('\u0000' to '\uffff' Unicode)
signed numeric integers
byte8-bit integer8-128  to  127
shortShort integer16-32,768  to  32,767
intInteger32-2,147,483,648  to  2,147,483,647
longLong integer64-9,233,372,036,854,775,808  to  9,233,372,036,854,775,807
signed floating point
floatSingle-precision float32varies
doubleDouble-precision float64varies

Naming Rules and Keywordsgo to top of page Top

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 a number.
  • The following reserved words used for literal values are unavailable for use as identifiers false, null and true.
  • You cannot use keywords recognized by the compiler. See the table below for the keywords you can't use.

Click a link in the table below to show lesson usage for any keyword you're interested in:

Java5 Keywords
abstractassertbooleanbreakbytecasecatchcharclassconst *
continuedefaultdodoubleelseenumextendsfinalfinallyfloat
forgoto *ifimplementsimportinstanceofintinterfacelongnative
newpackageprivateprotectedpublicreturnshortstaticstrictfpsuper
switchsynchronizedthisthrowthrowstransienttryvoidvolatilewhile

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 Typego to top of page Top

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 _BeginningJava5 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.

save boolean class

Compiling And Running Our Source File

Open your command line editor:

change to directory  cd c:\_BeginningJava5

compile BooleanType.java using the java compiler  javac BooleanType.java

run BooleanType.class using the java intepreter  java BooleanType

run boolean

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 Typego to top of page Top

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:\_BeginningJava5

run char

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 Typesgo to top of page Top

Java has 4 numeric integer types byte, short, int and long.

Integer Types
Type Meaning Bit Width Range
byte8-bit integer8-128  to  127
shortShort integer16-32,768  to  32,767
intInteger32-2,147,483,648  to  2,147,483,647
longLong integer64-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:\_BeginningJava5

run int 1

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:\_BeginningJava5

run int 2

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:\_BeginningJava5

run int 3

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 Typesgo to top of page Top

Java has 2 floating-point types float and double.

Integer Types
Type Meaning Bit Width Range
floatSingle-precision float32varies
doubleDouble-precision float64varies

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:\_BeginningJava5

run int 1

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 Literalsgo to top of page Top

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.

Integer Types
Type Examples
boolean
booleantrue or false
char
char16, 'G', 'a'    (numeric or a single character enclosed in single quotes)
signed integers
byteNegative or positive integers in the range -128  to  127
shortNegative or positive integers in the range -32,768  to  32,767
intNegative or positive integers in the range -2,147,483,648  to  2,147,483,647
longNegative 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
floatAppend a f or F to the number or it will be treated as type double.
25.23f, -1234.56F
double12.34, -56.72456
hexadecimal constants
byte, short, int, longCan be used with any integer type as long as it is in range for that type.
0xF, 0xFA
octal constants
byte, short, int, longCan 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

Primitive Variables Quizgo to top of page Top

Try the quiz below to test your knowledge of this lesson

Question 1 : Which is a valid declaration of a char type?
- A char type must be initialized as a numeric or a single character enclosed in single quotes.
Question 2 : An int can fit into a short?
- Integer types can fit into larger integer types but not smaller. So an int will not fit into a short.
Question 3 : Pick out the valid identifier?
- Identifiers can only start with a letter, the $ symbol or the _ symbol.
Question 4 : What are the two floating point primitive types?
- The two floating point primitive types are double and float.
Question 5 : Will the following code compile?

short s 65; byte b= 65; int i = s + b;
- Variable i is dynamically initialized at runtime from s and b so is fine.
Question 6 : What other integer types can a short fit into?
- A short can fit into an int and a long
Question 7 : What happens when we compile the following statement?

float f = 16.54;
- Doesn't compile as the compiler thinks we are passing a double to a float.
Question 8 : We can use numerics in any position of an identifier?
- You can't start an identifer with a numeric.
Status Bar Please select an answer

What's Next?

Have you noticed that all the variables we have used so far have been defined with the main() method? Variables defined in methods are known as local variables in Java. In the next lesson we look at method scope and what this means concerning our variables.

<<  Code Structure & Syntax                    Method Scope  >>

go to home page Java5 Tutor Homepage go to top of page Top