Primitive data types and classes
Please read the Object-Oriented Programming - OOP tutorials before this one.
Java is not a pure object-oriented language. Java is known as a hybrid language. This is because, as we shall see, not everything in Java is object oriented.
Data Types in Java
Programs work manipulating data. These data are of different classes or types.
Data types are for example: integers, real numbers, dates, etc... When the data is an object, the data type is the class to which it belongs.
In Java, there are other data types that are not objects. These data are the so-called Primitive types.
Primitive Types
In the following table, in the column on the left, we can see the primitive types. An easy way to differentiate them from the classes, is that they start with lowercase. These types are similar to the ones in C language or other object-oriented languages.
We do not need to create a primitive data type, using the instruction "new", as we do with an object. Nor is it possible to access any field or associated method. They haven´t got any.
Primitive data types are stored in memory on the Stack, instead of in the Heap memory, where objects are stored. This makes the management of the memory, easier and more efficient.
Primitive type |
Size in bytes |
Wrapper Class |
boolean |
Boolean |
|
char |
2 |
Character |
byte |
1 |
Byte |
short |
2 |
Short |
int |
4 |
Integer |
long |
8 |
Long |
float |
4 |
Float |
double |
8 |
Double |
void |
Void |
There is a Wrapper class, for each one of the primitive data type, which allows to store the same information, but using an object.
Objects and classes
A class, is the data type of an object, a mold that defines how the objects will be.
Once the object is created, we can access its fields and methods.
Java, has already a large number of defined classes, which are known as the Java API.
Some of these classes are: String, to store phrases or strings, Date to store dates and all the wrapper clases of the primitives types of the table above: Boolean, Character, Byte, Short, Integer, Long, Float, Double and Void:
To create an object Date in Java, just type "new Date ()", which returns an object Date.
Class definition
We can create our own classes, using the class keyword, followed by the name of the class and the class body.
The class body is enclosed in {}. The body can contain definitions of variables, methods and inner classes.
class MyClass { }
In future tutorials, we will see in more detail, how to define a class.