01 - Variables & Data Types
An introduction to variables and data types in Java programming.
Variables are containers that store data in your program. Think of them as labeled boxes where you can put different types of information.
What is a Variable?
A variable has three key components:
- Type: What kind of data it holds (e.g., integer, string, boolean)
- Name: The label you use to refer to the variable
- Value: The data it contains
Declaring/Creating Variables
In Java, you must declare a variable before using it, like you'd need a box before putting something in it. The syntax is:
int age;
age = 18;
int age = 18; // Declaration and assignment in one linePrimitive Data Types
You might wonder what "int" means. It's a primitive data type in Java. Java has 8 primitive data types. Here are the most important ones for modding:
| Data Type | Description | Example |
|---|---|---|
| int | Integer (whole numbers) | int score = 100; |
| double | Decimal numbers | double pi = 3.14; |
| boolean | True or false values | boolean isActive = true; |
| char | Single character | char grade = 'A'; |
| String | Sequence of characters (text) | String name = "Hytale"; |
Type Conversion
Sometimes you might not want a variable to stay the same type. You can convert between types:
Automatic
int num = 10;
double decimalNum = (double) num; // 10.0 - works automaticallyManual (Casting)
double decimalNum = 9.78;
int num = (int) decimalNum; // 9 - decimals are droppedConstants
If you want a variable that shouldn't change, use the final keyword:
final double PI = 3.14159;Convention: Constants use ALL_CAPS_WITH_UNDERSCORES.
Practice
It's best to practice what you just learnt - don't look above now and try to do this yourself. If you get stuck, look back up!
- Declare an integer variable named
livesand set it to 3. - Declare a double variable named
gravityand set it to 9.81. - Declare a boolean variable named
isGameOverand set it to false. - Convert the
livesvariable to a double and store it in a new variable namedlivesAsDouble. - Declare a constant named
MAX_LEVELand set it to 100.
Great! You've learned about variables and data types in Java. Now we're going to learn about operators and expressions in the next lesson.