Java Tutorials – Lesson 2: Primitive Data Types and Variables (Integer, double, float, and more)

Google+ Pinterest LinkedIn Tumblr +

Primitive Data Types

A primitive data type is a type of data that is essentially hard coded into the language and is represented with a reserved word(a word that has specific meaning and functionality in the language) in Java. Primitive data types are one of the building blocks of Java.

There are 8 primitive data types in Java:

Integer Types

  1. boolean-This data type holds true or false only. It is represented logically by 1 bit (0 for false, 1 for true).
  2. byte-This data type holds values between -128 to 127(integer only). It is represented by 8 bits in memory(2’s complement form).
  3. short-This data type holds values between -32,768 and 32,767. It is represented by 16 bits in memory(2’s complement form).
  4. int-This data type holds values between -2,147,483,648 and 2,147,483,647. It is represented by 32 bits in memory(2’s complement form).
  5. long-This data type holds values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. It is represented by 32 bits in memory(2’s complement form).
  6. char-This data type holds a 16 bit unicode character.

Decimal Types

  1. float-This data type is represented by 32 bits in memory. It can store decimal numbers typically with 7 significant figures. (example: 45.3453) This data type should not be used with extremely precise applications.
  2. double-This data type is represented by 64 bits in memory. It can store decimal numbers typically with 15 significant figures. (example: 45.3453) This data type should not be used with extremely precise applications.

Creating Variables

Variables, once declared, can be used throughout your program.

A variable is easy to declare and give a value. Several examples are below of creating a variable.

boolean myBool = true;

int myInt = 34342;

double myDouble = 349634.4564

The default value is the value that is automatically assigned if you do not assign a value. Values are always initialized to 0 or null. Even so, it is recommended that you ALWAYS assign a value to your variables as you declare them.

Declaring Constants

A constant is a value that does not change. An example of this is the value PI, 3.14159… To declare a constant, use the final keyword.

Example:

final double PI = 3.14159;

The value of constants cannot be changed during program run! If you attempt to do so, the program will not compile, or if it does, the program will stop running and give you an error.

Isn’t that much easier than typing 3.14159 several times throughout your program!

Naming Variables

Now that you know how to declare and assign a variable, let’s go into detail about what variable names are allowed.

  • The variable cannot be a reserved word. A list of all reserved words can be found below.
  • The variable can contain any combination of letters, numbers,
Share.

About Author

Leave A Reply