Primitives and Arrays
Explore Java primitive types such as int, byte, float, and boolean, and understand their sizes and uses. Learn how to create and manipulate arrays of primitives and objects, including printing techniques and when to use ArrayList for dynamic sizing.
We'll cover the following...
Primitives
Primitive types in Java refer to different ways to store numbers:
char: A single character, such as “A” (the letter A).
byte: A number from -128 to 127 (8 bits). This is typically a way to store or transmit raw data.
short: A 16-bit signed integer. It has a maximum value of around 32,000, precisely 32,767.
int: A 32-bit signed integer. Its maximum is around .
long: A 64-bit signed integer. It has a maximum of .
float: A 32-bit floating point number. This is a non-precise value that is used for things like simulations.
double: It’s like float but with 64-bits.
boolean: It has only two possible values:trueandfalse(much like a bit).
Arrays
In Java, we can define arrays of primitives or classes. For example, String[] strArray = {"a", "b", "c"}; creates an array of three Strings. Once we define an array, we cannot directly change its length. If we need a list of expanding size, we can instead use java.util.ArrayList.
In this program, we declare an array strArrray with strings "a", "b", and "c". The for loop is used to print the elements one-by-one. We can also print the whole array with the System.out.println(Arrays.toString(array)) command.