Programming & Scripting Tutorials

Java: Basic Data Types





In java there are two data types, primitives and aggregates, today we will be looking at the simple primitive type.
A data type represents either a single piece of a selection of data, primitives hold only a single piece of data.
There are eight types of primitives in the java language:

int
long
double
byte
float
short
char
boolean

Today we will be covering the main few.

int

Ints (integers) in java are able to hold positive or negative numbers within -2146473648 to 2147483647


double

Doubles can hold positive or negative numbers numbers with decimal places within a certain range.

char

Chars (charactors) can hold one letter (or one ASCII charctor).

boolean

Contains a true or false value.

long

This can hold VERY, VERY long integers; this is the datatype you will need for very long integers (usually int will do)

byte

These hold very small integers, only around 100 each way (positive and negative).

float

The float is a lot like the double apart from it holds slightly smaller numbers.

short

Short's are the next step up from bytes, they are still fairly small, but bigger than byte (smaller that integer).

-

In java you declare a variable like so:

DATATYPE name;


Here are the examples we will be using:

int IntegerVariableOne;
double DoubleVariableOne;
char CharVariableOne;
boolean BoolVariableOne;

At the moment the variable is declared but contains no value. To assign the variable a value we can either do it at declaration like so:

DATATYPE name = data;

In our examples:

int IntegerVariableOne = 12;
double DoubleVariableOne = 1.92;
char CharVariableOne = "a";
boolean BoolVariableOne = true;


or we can initialise the variables after declaration (you can also change the variables value using this method):

name = data;


For example:

IntegerVariableOne = 92;



If we wanted to store any more than one character we couldnt use a char, we would have to use a string.
Strings however are not a primitive datatype and is not built into the language, string usage is simply an object which comes with the language; Since strings are so commonly used I will go over them to.

Its very simple, you just use the datatype "String"!


This Java tutorial was written by


Back to Java

Advertisement: