2.2. Variables and Data Types
Variables
A variable is a fundamental concept in any programming language. Think of it as a named container or a labeled box that holds a value, which can be changed during the execution of the program.
- Purpose: To store data in the computer's memory so that it can be used and manipulated later in the program.
- Analogy: A variable is like a mailbox. The variable's name is the address on the mailbox, and the data it holds is the mail inside. You can change the mail inside, but the address remains the same.
Declaration and Initialization
Using a variable in Java is a two-step process (which can be combined).
Declaration: This is where you tell the compiler the variable's name and the type of data it will hold. You reserve the "box" and label it.
- Syntax:
dataType variableName;
- Example:
int age;
(Declares a variable namedage
that will hold an integer)
- Syntax:
Initialization: This is the first time you assign a value to the variable. You are putting a value into the "box".
- Syntax:
variableName = value;
- Example:
age = 25;
(Puts the value25
into the variableage
)
- Syntax:
You can also declare and initialize a variable in a single statement, which is the most common practice.
- Syntax:
dataType variableName = value;
- Example:
int score = 100;
Identifiers
Rules for naming variables (identifiers) in Java are strict:
- Must begin with a letter (a-z, A-Z), underscore (_), or a dollar sign ($).
- Subsequent characters can be letters, digits, underscores, or dollar signs.
- Cannot be a Java keyword (e.g.,
int
,class
,public
). - Case-sensitive (
myVar
andmyvar
are different).
Conventions (not rules, but best practices for readable code):
- Use meaningful names (e.g.,
userName
instead ofx
). - Follow camelCase convention: start with a lowercase letter and capitalize the first letter of each subsequent word (e.g.,
firstName
,totalStudentCount
).
Primitive Data Types
Java has eight primitive data types, which are the basic building blocks for storing simple values. They are built into the language.
Data Type | Size (bits) | Description | Range | Example Literals |
---|---|---|---|---|
byte | 8 | Very small integer | -128 to 127 | byte b = 100; |
short | 16 | Small integer | -32,768 to 32,767 | short s = 5000; |
int | 32 | Standard integer | ~-2.1 billion to ~2.1 billion | int i = 100000; |
long | 64 | Large integer | Very large | long l = 1234567890L; (Note the 'L') |
float | 32 | Single-precision decimal | ~6-7 decimal digits | float f = 3.14f; (Note the 'f') |
double | 64 | Double-precision decimal | ~15 decimal digits | double d = 3.1415926535; |
char | 16 | Single character | Unicode character | char grade = 'A'; (Single quotes) |
boolean | ~1 | Logical value | true or false | boolean isJavaFun = true; |
Key Points:
- For whole numbers,
int
is the most commonly used type. Uselong
only if the number is very large. - For decimal numbers,
double
is the default and most common choice. Usefloat
only if you need to save memory in large arrays. - The
char
data type uses single quotes (' '
), not double quotes. - The
boolean
type can only betrue
orfalse
; it is not a number (unlike in some other languages).
Reference Data Types
Unlike primitive types, reference types do not store the actual data itself. Instead, they store a reference (like a memory address) to the location where the data is stored.
- Examples: Strings, Arrays, Classes, Interfaces.
- The
String
Class: The most common reference type. It is used to store a sequence of characters (text).- Example:
String greeting = "Hello World";
- Note: String literals are enclosed in double quotes (
" "
).
- Example:
Key Difference: Primitive types hold values. Reference types hold addresses of objects.
Constants
A constant is a variable whose value cannot be changed once it is assigned. You create a constant using the final
keyword.
- Syntax:
final dataType CONSTANT_NAME = value;
- Example:
final double PI = 3.14159;
- Convention: Constant names are written in UPPERCASE letters with underscores separating words (e.g.,
MAX_SPEED
).
Type Casting
Type casting is converting a value from one data type to another. There are two types:
Widening Casting (Implicit): Happens automatically when converting a smaller type to a larger type. It is safe because there is no risk of data loss.
- Example:
int myInt = 9; double myDouble = myInt; // int -> double
- Example:
Narrowing Casting (Explicit): Must be done manually by the programmer. Converting a larger type to a smaller type risks data loss, so you must explicitly confirm the cast by placing the target type in parentheses before the value.
- Syntax:
targetType variableName = (targetType) value;
- Example:
double myDouble = 9.78; int myInt = (int) myDouble; // double -> int (myInt becomes 9)
- Syntax:
The var
Keyword (Java 10+)
Since Java 10, you can use var
to declare local variables. The compiler infers the variable's type from the initializer on the right-hand side.
- Example:
var message = "Hello";
// compiler infersmessage
asString
var count = 10;
// compiler inferscount
asint
- Important:
var
can only be used for local variables inside methods when they are declared and initialized on the same line. The variable still has a strong type; it is not "dynamically typed".
Example Code Snippet
public class VariablesExample {
public static void main(String[] args) {
// Primitive Types
int studentCount = 30;
double averageScore = 85.5;
char finalGrade = 'A';
boolean isPassed = true;
// Reference Type (String)
String className = "Introduction to Java";
// Constant
final int MAX_CLASS_SIZE = 40;
// Type Casting
double price = 19.99;
int discountedPrice = (int) price; // Explicit cast, value becomes 19
// var keyword
var instructor = "Dr. Smith"; // Inferred as String
// Printing variables
System.out.println("Class: " + className);
System.out.println("Discounted Price: $" + discountedPrice);
}
}