Module 2: Variables, Data Types, and Operators
Lesson focusPrimitive Data Types and Variables
A deep dive into Java's 8 primitive types, how to declare and initialize variables, and how these types are stored in memory.
What is a Variable? A variable is a container that holds a value. In Java, every variable must have a specific data type, which tells the compiler how much memory to reserve for it and what kind of data it can store.
Statically-Typed Language: Java is a statically-typed language. This means you must declare the type of a variable before you can use it, and the type cannot be changed later. This helps catch errors early, during compilation, rather than at runtime.
The 8 Primitive Types: Java has eight fundamental data types, known as primitive types. They are the most basic building blocks for data.
- Integer Types: For whole numbers.
byte: 8-bit. Range: -128 to 127. Use for saving memory in large arrays.
short: 16-bit. Range: -32,768 to 32,767. Also for memory saving.
int: 32-bit. Range: -2.1 billion to 2.1 billion. The most commonly used integer type.
long: 64-bit. For very large whole numbers. Must be appended with anL(e.g.,long bigNumber = 3000000000L;).
- Floating-Point Types: For numbers with fractional parts.
float: 32-bit. For single-precision decimals. Must be appended with anf(e.g.,float pi = 3.14f;).
double: 64-bit. For double-precision decimals. The default and most common type for decimal numbers.
- Other Types:
boolean: Representstrueorfalsevalues. Used for logical conditions.
char: 16-bit Unicode character. Can hold a single character, enclosed in single quotes (e.g.,char grade = 'A';).
Declaration and Initialization:
- Declaration:
int myAge;(Reserves memory for an integer namedmyAge).
- Initialization:
myAge = 30;(Assigns a value to the variable).
- Combined:
int myAge = 30;(Declares and initializes in one step).
Mini-Exercise: Declare and initialize a variable for each of the 8 primitive types. Print each variable to the console to see its value.
int score = 100;
double price = 19.99;
char initial = 'J';
boolean isLoggedIn = false;
long worldPopulation = 7800000000L;
System.out.println("Score: " + score);
System.out.println("Logged In: " + isLoggedIn);Lesson quiz