CSA: Variables and data types
Variables and Data Types in Java
Introduction to Data Types
In Java, there are several data types used to store data, in addition to strings.
String literal: A sequence of characters enclosed in double quotations.
The key fundamental data types in Java include:
int: used for integers (whole numbers).
double: used for floating-point numbers (decimal values).
char: used for single characters.
boolean: used for true or false values.
Understanding Variables
Variables: Can be thought of as containers (boxes) with a name used to store values.
Every variable has a:
Name: The identifier for the variable.
Type: The data type that the variable holds.
Value: The actual data stored in the variable.
Example:
int numapples = 5;Here,
numapplesis the name;intis the type;5is the value.
Declaring Variables
To create a variable, the following steps are essential:
Determine the type of data to be stored (e.g., int, double).
Name the variable carefully to provide clarity on its purpose.
Naming Variables
Naming Conventions:
Use letters, dollar signs, or underscores to start the variable name.
Avoid starting variable names with numbers, as this will result in errors.
Follow lower camel case: The first word is in lowercase while each subsequent word starts with uppercase.
Examples:
numApplesis acceptable, while1stApplesis not.
Case Sensitivity
Variable names are case sensitive.
For example,
numApplesandNumApplesare distinct and treated differently in the program.
Ensure to match the exact spelling when referencing variables.
Initializing Variables
Once declared, variables can be initialized (assigned a value).
Important rules include:
The data type in the declaration must match the type of the assigned value.
Example of conflict:
Declaring as boolean, but assigning an int value results in an error.
Variable Assignment Examples
Variables can be initialized at the time of declaration:
int numapples = 5;
Alternatively, they can be initialized after declaration:
int numapples; numapples = 5;
Values can be changed later but require careful assignment to avoid type mismatches.
Final Variables
Use the keyword final to declare a constant variable that cannot be changed:
Example:
final int maxApples = 10;
Attempt to modify this variable after its initial assignment will cause an error and prevent changes.
This is often a security measure in complex coding environments to protect specific values from alteration.
Conclusion
Understanding the basic variable types and proper usage is key to programming effectively in Java.