Search⌘ K
AI Features

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).
Java
public class main {
public static void main(String[] args) {
char hello = 'A';
System.out.println(hello);
}
}
  • byte: A number from -128 to 127 (8 bits). This is typically a way to store or transmit raw data.
Java
public class main {
public static void main(String[] args) {
byte num = 100;
System.out.println(num);
}
}
  • short: A 16-bit signed integer. It has a maximum value of around 32,000, precisely 32,767.
Java
public class main {
public static void main(String[] args) {
short num = 32212;
System.out.println(num);
}
}
  • int: A 32-bit signed integer. Its maximum is around 2312^{31}.
Java
public class main {
public static void main(String[] args) {
int score = 4;
System.out.println(score);
}
}
  • long: A 64-bit signed integer. It has a maximum of 2632^{63}.
Java
public class main {
public static void main(String[] args) {
long num = 33000;
System.out.println(num);
}
}
  • float: A 32-bit floating point number. This is a non-precise value that is used for things like simulations.
Java
public class main {
public static void main(String[] args) {
float num = 1.4233f; // "f" is used to assign the number to float data type
System.out.println(num);
}
}
  • double: It’s like float but with 64-bits.
Java
public class main {
public static void main(String[] args) {
double num = 1.24;
System.out.println(num);
}
}
  • boolean: It has only two possible values: true and false (much like a bit).
Java
public class main {
public static void main(String[] args) {
boolean b = true;
System.out.println(b);
}
}

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.

Java
public class main {
public static void main(String[] args) {
String[] strArray = {"a", "b", "c"}; //declaring an array
for (String element: strArray) {
System.out.println(element); //printing it element wise
}
}
}

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.