Primitive Data Types
Let's go into the details of some of the primitive data types.
We'll cover the following
As we discussed briefly in the previous lesson, primitive data types are the most basic types of data in Java. Primitive variables directly store primitive values. In the context of the AP Computer Science exam, we will look into three primitive data types: int
, double
, and boolean
.
All of these types are constructed using a binary notation (i.e., base digits: and ). However, the representation of each varies.
int
type in Java
We use the int
type variable to represent integers. The size of an int
type variable is bytes, or bits. You can assign both positive and negative integer values to such a variable. It uses two’s complement representation. Let’s briefly take a look at this representation.
You may recall the binary representation of numbers from school but feel free to take a look at
You can represent any positive integer in binary notation, but what about the negative integers? That’s where two’s complement comes in handy.
Note: To get information about 2’s complement, check out this shot.
Because of two’s complement representation, the int
can take values from the range of to .
📌 Note: For integers of larger magnitude, Java has the data type,
long
. It has a size of 8 bytes, or 64 bits, and its range is to .
Use cases
The int
data type can be used whenever you need to represent a discrete number. For example:
- To represent scores in different games
- To represent dates and time in seconds
- To keep count of various events
Syntax
In Java, you can declare an int
type variable and assign it a value in the following manner:
Get hands-on with 1200+ tech skills courses.