As explained in the previous chapter, a variable in Java must be a specified data type. Data types are divided into two groups:
byte, short, int, long, float, double, boolean and char.String, Arrays, and Classes.A primitive data type specifies the size and type of variable values, and it has no additional methods. They are the most basic data types available in Java.
Integer types store whole numbers, positive or negative, without decimals.
byte: Stores whole numbers from -128 to 127. Saves memory. (1 byte)short: Stores whole numbers from -32,768 to 32,767. (2 bytes)int: The most commonly used integer type. Stores whole numbers from -2,147,483,648 to 2,147,483,647. (4 bytes)long: Used when int is not large enough. Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. The value should end with an 'L'. (8 bytes)byte myByte = 100; short myShort = 5000; int myInt = 100000; long myLong = 15000000000L; System.out.println(myLong);
Floating-point types represent numbers with a fractional part.
float: Stores fractional numbers. Sufficient for 6 to 7 decimal digits. The value should end with an 'f'. (4 bytes)double: The most commonly used float type. Sufficient for about 15 decimal digits. The value can end with a 'd' (optional). (8 bytes)float myFloat = 5.75f; double myDouble = 19.99d; System.out.println(myFloat);
boolean: Can only have one of two values: true or false. It is often used for conditional testing. (1 bit)char: Used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c'. (2 bytes)
boolean isJavaFun = true;
char myGrade = 'B';
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("My grade is: " + myGrade);
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
String).null.Examples of non-primitive types include Strings, Arrays, Classes, Interfaces, etc.
public class Main {
public static void main(String[] args) {
// The 'greeting' variable holds a reference to a String object
String greeting = "Hello World";
// We can call methods on the object
System.out.println("The length of the string is: " + greeting.length());
}
}